2009-10-01 99 views

回答

8

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())至 一個唯一的哈希能夠識別對象實例。正如我上面所說的:一個字符串根本不是一個對象,因此它沒有實例哈希。字符串的唯一性可以通過比較字符串值來檢查 - 當兩個字符串包含相同的字節集時,它們是相等的。

1

將字符串包裝在stdClass中?

$dummy_object = new stdClass(); 
$dummy_object->string = $whatever_string_needs_to_be_tracked; 
$splobjectstorage->attach($dummy_object); 

但是,即使字符串相同,以這種方式創建的每個對象仍然是唯一的。

如果你需要擔心重複的字符串,也許你應該使用散列(關聯數組)來跟蹤它們呢?

+0

你能提供一些樣品關於如何存儲一組唯一字符串然後迭代它們的代碼?爲什麼在PHP中這麼辛苦? – erotsppa 2009-10-01 03:28:21

+2

難道你不能把它們存儲在一個數組中嗎?似乎你讓事情變得複雜一些;) – 2009-10-01 04:55:18

0
$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用於跟蹤對象的唯一實例,並且在不使用字符串的情況下,對於您想要完成的操作(在我看來),這有點矯枉過正。

希望有幫助!

5

這是一個對象存儲。字符串是標量。所以使用SplString

0

或者只是實例化你的字符串與__toString對象()方法 - 這樣你可以讓他們都 - 對象,並把它作爲字符串的能力(的var_dump,回聲)..