有人建议使用SplObjectStorage来跟踪一组独特的事物。太棒了,除非它不适用于字符串。一个错误说“SplObjectStorage :: attach()期望参数1是对象,在59行fback.php中给出的字符串”SplObjectStorage不适用于String,该怎么办?
任何想法?
有人建议使用SplObjectStorage来跟踪一组独特的事物。太棒了,除非它不适用于字符串。一个错误说“SplObjectStorage :: attach()期望参数1是对象,在59行fback.php中给出的字符串”SplObjectStorage不适用于String,该怎么办?
任何想法?
SplObjectStorage
就是它的名字所说的:存储对象的存储类。与其他编程语言相比,strings
不是PHP中的对象,它们就是字符串;-)。因此,将字符串存储在SplObjectStorage
中是没有意义的 - 即使您将字符串包装在类stdClass
的对象中。
存储一组唯一字符串si以便以字符串作为关键字和值(如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;
}
// ...
}
通过你的SAN模拟SplObjectStorage
的行为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()
)至 一个唯一的哈希能够识别对象实例。正如我上面所说的:一个字符串根本不是一个对象,因此它没有实例哈希。字符串的唯一性可以通过比较字符串值来检查 - 当两个字符串包含相同的字节集时,它们是相等的。
将字符串包装在stdClass中?
$dummy_object = new stdClass();
$dummy_object->string = $whatever_string_needs_to_be_tracked;
$splobjectstorage->attach($dummy_object);
但是,即使字符串相同,以这种方式创建的每个对象仍然是唯一的。
如果你需要担心重复的字符串,也许你应该使用散列(关联数组)来跟踪它们呢?
$myStrings = array();
$myStrings[] = 'string1';
$myStrings[] = 'string2';
...
foreach ($myStrings as $string)
{
// do stuff with your string here...
}
如果你想确保数组中字符串的唯一性,你可以做几件事情......首先是简单地使用array_unique()。这,或者你可以创建一个字符串作为键和值的关联数组:如果你想成为这个面向对象
$myStrings = array();
$myStrings['string1'] = 'string1';
...
,你可以这样做:
class StringStore
{
public static $strings = array();
// helper functions, etc. You could also make the above protected static and write public functions that add things to the array or whatever
}
然后,在你的代码,你可以做的东西,如:
StringStore::$strings[] = 'string1';
...
并重复同样的方式:
foreach (StringStore::$strings as $string)
{
// whatever
}
SplObjectStorage用于跟踪对象的唯一实例,并且在不使用字符串的情况下,对于您想要完成的操作(在我看来),这有点矫枉过正。
希望有帮助!
这是一个对象存储。字符串是标量。所以使用SplString。
或者只是实例化你的字符串与__toString对象()方法 - 这样你可以让他们都 - 对象,并把它作为字符串的能力(的var_dump,回声)..
你能提供一些样品关于如何存储一组唯一字符串然后迭代它们的代码?为什么在PHP中这么辛苦? – erotsppa 2009-10-01 03:28:21
难道你不能把它们存储在一个数组中吗?似乎你让事情变得复杂一些;) – 2009-10-01 04:55:18