题
有人建议使用 SplObjectStorage 来跟踪一组独特的事物。很好,但它不适用于字符串。错误提示“ SplObjectStorage::attach() 期望参数 1 为对象,字符串在 fback.php 第 59 行给出”
有任何想法吗?
解决方案
这 SplObjectStorage
正如它的名字所说:用于存储对象的存储类。与其他一些编程语言相比 strings
不是 PHP 中的对象,它们是字符串;-)。因此,将字符串存储在 a 中是没有意义的。 SplObjectStorage
- 即使你将字符串包装在类的对象中 stdClass
.
存储唯一字符串集合的最佳方法是使用数组(如哈希表),并将字符串作为键和值(如建议的那样) 伊恩·塞尔比).
$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,回声)..