2010-10-28 64 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