加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 18:27:16 所属栏目:PHP教程 来源:网络整理
导读:有人建议使用SplObjectStorage来跟踪一组独特的东西.很好,除了它不适用于字符串.错误说“SplObjectStorage :: attach()期望参数1是对象,在第59行的fback.php中给出的字符串” 有任何想法吗? SplObjectStorage 就是它的名字所说的:用于存储对象的存储类.与
有人建议使用SplObjectStorage来跟踪一组独特的东西.很好,除了它不适用于字符串.错误说“SplObjectStorage :: attach()期望参数1是对象,在第59行的fback.php中给出的字符串”

有任何想法吗?

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

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

$myStrings = array();
$myStrings['string1'] = 'string1';
$myStrings['string2'] = 'string2';
// ...

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

class UniqueStringStorage // perhaps implement Iterator
{
    protected $_strings = array();

    public function add($string)
    {
        if (!array_key_exists($string,$this->_strings)) {
            $this->_strings[$string] = $string;
        } else {
            //.. handle error condition "adding same string twice",e.g. throw exception
        }
        return $this;
    }

    public function toArray()
    {
        return $this->_strings;
    }

    // ... 
}

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

$ob1 = new stdClass();
$id1 = spl_object_hash($ob1);
$ob2 = new stdClass();
$id2 = spl_object_hash($ob2);
$objects = array(
    $id1 => $ob1,$id2 => $ob2
);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读