2010-10-28 100 views
4

$陣列[(對象)$ OBJ] = $ OTHER_OBJ;複雜類型作爲數組索引

PHP陣列僅具有標量數據類型,象int,字符串,浮點數,布爾值,空索引工作。我不能像其他語言那樣使用對象作爲數組索引嗎?那麼如何實現一個對象 - >對象映射?

(不過,我覺得我已經看到了這樣的事情在這裏,但不記得準確,我的搜索創意陳舊。)

回答

2

這聽起來像你想重新發現SplObjectStorage類,它可以從對象到其他數據(在你的情況下,其他對象)提供的地圖。

它讓你甚至可以用你想要的語法像$store[$obj_a] = $obj_b實現了ArrayAccess接口。哈哈!

+0

雖然特定的功能僅適用於> 5.3 – mario 2010-10-30 18:36:15

2

如果您需要能夠重新創建對象從鑰匙開始,您可以使用serialize($obj)作爲鑰匙。重新創建對象調用unserialize

1

依然沒有找到原來的,但記得實際的招,所以我重新實現它:
(我的互聯網連接趴下昨天給我的時間)

class FancyArray implements ArrayAccess { 

    var $_keys = array(); 
    var $_values = array(); 

    function offsetExists($name) { 
     return $this->key($name) !== FALSE; 
    } 

    function offsetGet($name) { 
     $key = $this->key($name); 
     if ($key !== FALSE) { 
      return $this->_values[ $key ]; 
     } 
     else { 
      trigger_error("Undefined offset: {{$name}} in FancyArray __FILE__ on line __LINE__", E_USER_NOTIC 
      return NULL; 
     } 
    } 

    function offsetSet($name, $value) { 
     $key = $this->key($name); 
     if ($key !== FALSE) { 
      $this->_values[$key] = $value; 
     } 
     else { 
      $key = end(array_keys($this->_keys)) + 1; 
      $this->_keys[$key] = $name; 
      $this->_values[$key] = $value; 
     } 
    } 

    function offsetUnset($name) { 
     $key = $this->key($name); 
     unset($this->_keys[$key]); 
     unset($this->_values[$key]); 
    } 

    function key($obj) { 
     return array_search($obj, $this->_keys); 
    } 
} 

它基本上ArrayAcces和貶低用於鍵的數組和用於值的數組。非常基本的,但它允許:

$x = new FancyArray(); 

$x[array(1,2,3,4)] = $something_else; // arrays as key 

print $x[new SplFileInfo("x")]; // well, if set beforehand