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