[关闭]
@a5635268 2016-03-13T17:39:31.000000Z 字数 1622 阅读 1195

【SPL标准库专题(9)】 Datastructures:SplObjectStorage

SPL


PHP SPL SplObjectStorage是用来存储一组对象的,特别是当你需要唯一标识对象的时候。
PHP SPL SplObjectStorage类实现了Countable,Iterator,Serializable,ArrayAccess四个接口。可实现统计、迭代、序列化、数组式访问等功能。

类摘要

  1. SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess {
  2. /* 方法 */
  3. public void addAll ( SplObjectStorage $storage )
  4. // ↓↓加入对象
  5. public void attach ( object $object [, mixed $data = NULL ] )
  6. // ↓↓检查是否包含指定对象
  7. public bool contains ( object $object )
  8. // ↓↓移除对象
  9. public void detach ( object $object )
  10. // ↓↓返回一串哈希值,每次调用的时候该串哈希值都在改变
  11. public string getHash ( object $object )
  12. public mixed getInfo ( void )
  13. public int count ( void )
  14. public object current ( void )
  15. public int key ( void )
  16. public void next ( void )
  17. public bool offsetExists ( object $object )
  18. public mixed offsetGet ( object $object )
  19. public void offsetSet ( object $object [, mixed $data = NULL ] )
  20. public void offsetUnset ( object $object )
  21. public void removeAll ( SplObjectStorage $storage )
  22. public void removeAllExcept ( SplObjectStorage $storage )
  23. public void rewind ( void )
  24. public string serialize ( void )
  25. public void setInfo ( mixed $data )
  26. public void unserialize ( string $serialized )
  27. public bool valid ( void )
  28. }

Example

  1. # Example1:
  2. class A {
  3. public $i;
  4. public function __construct($i) {
  5. $this->i = $i;
  6. }
  7. }
  8. $a1 = new A(1);
  9. $a2 = new A(2);
  10. $a3 = new A(3);
  11. $a4 = new A(4);
  12. $container = new SplObjectStorage();
  13. //SplObjectStorage::attach 添加对象到Storage中
  14. $container->attach($a1);
  15. $container->attach($a2);
  16. $container->attach($a3);
  17. //SplObjectStorage::detach 将对象从Storage中移除
  18. $container->detach($a2);
  19. //SplObjectStorage::contains用于检查对象是否存在Storage中
  20. var_dump($container->contains($a1)); //true
  21. var_dump($container->contains($a4)); //false
  22. //遍历
  23. $container->rewind();
  24. while($container->valid()) {
  25. var_dump($container->current());
  26. var_dump($container->getInfo());
  27. $container->next();
  28. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注