PHP SplObjectStorage使用实例
程序员文章站
2023-11-17 13:14:34
php spl splobjectstorage是用来存储一组对象的,特别是当你需要唯一标识对象的时候。
php spl splobjectstorage类实现了coun...
php spl splobjectstorage是用来存储一组对象的,特别是当你需要唯一标识对象的时候。
php spl splobjectstorage类实现了countable,iterator,serializable,arrayaccess四个接口。可实现统计、迭代、序列化、数组式访问等功能。
看下面一个简单的例子:
class a { public $i; public function __construct($i) { $this->i = $i; } } $a1 = new a(1); $a2 = new a(2); $a3 = new a(3); $a4 = new a(4); $container = new splobjectstorage(); //splobjectstorage::attach 添加对象到storage中 $container->attach($a1); $container->attach($a2); $container->attach($a3); //splobjectstorage::detach 将对象从storage中移除 $container->detach($a2); //splobjectstorage::contains用于检查对象是否存在storage中 var_dump($container->contains($a1)); //true var_dump($container->contains($a4)); //false //遍历 $container->rewind(); while($container->valid()) { var_dump($container->current()); $container->next(); }