phpcollections
v1.3.0
phpcollections是一组数据结构,旨在让您在使用 PHP 和大量数据时变得更轻松。受到 Java 或 C# 等语言的启发, phpcollections提供了 List、Map、Stack 等数据结构,请查看!
PHP >= 7.2
composer require "maxalmonte14/ phpcollections "
想象一下,您正在存储 Post 对象以便像这样获取。
$ posts [] = new Post ( 1 , ' PHP 7.2 release notes ' );
$ posts [] = new Post ( 2 , ' New Laravel 5.5 LTS make:factory command ' );
一切都很好!但也许您由于某种神秘的原因犯了一个错误,添加了一个非 Post 对象。
$ posts [] = 5 // This is not even an object!
当您尝试获取 posts 数组时,您就会遇到麻烦。
< ?php foreach($posts as $post): ? >
< tr >
<!-- this gonna fail when $post == 5! -->
< td > < ?= $post- > id; ? > </ td >
< td > < ?= $post- > title; ? > </ td >
</ tr >
< ?php endforeach ? >
幸运的是phpcollections存在。
$ posts = new GenericList (
Post::class,
new Post ( 1 , ' PHP 7.2 release notes ' ),
new Post ( 2 , ' New Laravel 5.5 LTS make:factory command ' )
);
$ posts -> add ( 5 ); // An InvalidArgumentException is thrown!
当然还有更灵活的数据结构,比如ArrayList。
$ posts = new ArrayList ();
$ posts -> add ( new Post ( 1 , ' PHP 7.2 release notes ' ));
$ posts -> add ( new Post ( 2 , ' New Laravel 5.5 LTS make:factory command ' ));
$ posts -> add ( 5 ); // Everything is fine, I need this 5 anyway