微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

有人建议使用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())存储唯一的哈希值能够识别对象实例.如上所述:字符串根本不是对象,因此它没有实例哈希.可以通过比较字符串值来检查字符串的唯一性 – 当两个字符串包含相同的字节集时,它们是相等的.

原文地址:https://www.jb51.cc/php/135878.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐