有人建议使用 SplObjectStorage 来跟踪一组独特的事物。很好,但它不适用于字符串。错误提示“SplObjectStorage::attach() 期望参数 1 是对象,第 59 行的 fback.php 中给出的字符串”
有任何想法吗?
这SplObjectStorage
就是它的名字所说的:用于存储对象的存储类。与其他一些编程语言strings
相比,PHP 中的对象不是对象,它们是字符串;-)。因此,将字符串存储在 a- 中是没有意义的,SplObjectStorage
即使您将字符串包装在 class 的对象中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
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()
)存储一个唯一的哈希,以便能够识别对象实例。正如我上面所说:字符串根本不是对象,因此它没有实例哈希。可以通过比较字符串值来检查字符串的唯一性——当两个字符串包含相同的字节集时,它们是相等的。
这是一个对象存储。字符串是标量。所以使用SplString。
将字符串包装在 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 用于跟踪对象的唯一实例,除了不使用字符串之外,这对于您要完成的任务来说有点过分(在我看来)。
希望有帮助!
或者也许只是使用 __toString() 方法将您的字符串实例化为一个对象 - 这样您就可以同时拥有它们 - 对象和将其用作字符串的能力(var_dump,echo)..