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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...