PHP SplObjectStorage使用实例

SplObjectStorage是SPL标准库中的数据结构对象容器,用来存储一组对象,特别是当你需要唯一标识对象的时候,需要的朋友可以参考下:

PHP SPL SplObjectStorage类实现了Countable,Iterator,Serializable,ArrayAccess四个接口。可实现统计、迭代、序列化、数组式访问等功能。

看下面一个简单的例子:

 1 php
 2 class A {
 3   public $i;
 4   public function __construct($i) {
 5     $this->i = $i;
 6   }
 7 }
 8   
 9 $a1 = new A(1);
10 $a2 = new A(2);
11 $a3 = new A(3);
12 $a4 = new A(4);
13   
14 $container = new SplObjectStorage();
15   
16 //SplObjectStorage::attach 添加对象到Storage中
17 $container->attach($a1);
18 $container->attach($a2);
19 $container->attach($a3);
20   
21 //SplObjectStorage::detach 将对象从Storage中移除
22 $container->detach($a2);
23   
24 //SplObjectStorage::contains用于检查对象是否存在Storage中
25 var_dump($container->contains($a1)); //true
26 var_dump($container->contains($a4)); //false
27   
28 //遍历
29 $container->rewind();
30 while($container->valid()) {
31   var_dump($container->current());
32   $container->next();
33 }

 

你可能感兴趣的:(PHP SplObjectStorage使用实例)