php – SplObjectStorage不能与String一起使用,该怎么办?

前端之家收集整理的这篇文章主要介绍了php – SplObjectStorage不能与String一起使用,该怎么办?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人建议使用SplObjectStorage来跟踪一组独特的东西.很好,除了它不适用于字符串.错误说“SplObjectStorage :: attach()期望参数1是对象,在第59行的fback.PHP中给出的字符串”

有任何想法吗?

SplObjectStorage就是它的名字所说的:用于存储对象的存储类.与其他一些编程语言相反,字符串不是PHP中的对象,它们是字符串;-).因此,将字符串存储在SplObjectStorage中是没有意义的 – 即使将字符串包装在类stdClass的对象中也是如此.

存储一组唯一字符串的最佳方法是使用数组(作为哈希表),以字符串作为键和值(如Ian Selby所示).

  1. $myStrings = array();
  2. $myStrings['string1'] = 'string1';
  3. $myStrings['string2'] = 'string2';
  4. // ...

但是,您可以将此功能包装到自定义类中:

  1. class UniqueStringStorage // perhaps implement Iterator
  2. {
  3. protected $_strings = array();
  4.  
  5. public function add($string)
  6. {
  7. if (!array_key_exists($string,$this->_strings)) {
  8. $this->_strings[$string] = $string;
  9. } else {
  10. //.. handle error condition "adding same string twice",e.g. throw exception
  11. }
  12. return $this;
  13. }
  14.  
  15. public function toArray()
  16. {
  17. return $this->_strings;
  18. }
  19.  
  20. // ...
  21. }

顺便说一下,你可以模拟SplObjectStorage for PHP的行为< 5.3.0并更好地了解它的作用.

  1. $ob1 = new stdClass();
  2. $id1 = spl_object_hash($ob1);
  3. $ob2 = new stdClass();
  4. $id2 = spl_object_hash($ob2);
  5. $objects = array(
  6. $id1 => $ob1,$id2 => $ob2
  7. );

SplObjectStorage为每个实例(如spl_object_hash())存储唯一的哈希值能够识别对象实例.如上所述:字符串根本不是对象,因此它没有实例哈希.可以通过比较字符串值来检查字符串的唯一性 – 当两个字符串包含相同的字节集时,它们是相等的.

猜你在找的PHP相关文章