复杂类型作为数组索引

Complex type as array index

提问人:mario 提问时间:10/29/2010 更新时间:5/30/2023 访问量:675

问:

$array[(对象)$obj] = $other_obj;

PHP 数组仅适用于具有标量数据类型(如 int、string、float、boolean、null)的索引。我不能像使用其他语言一样使用对象作为数组索引?那么,如何实现对象-对象>对象映射呢?

(我虽然在这里看到过类似的东西,但记不清了,我的搜索创造力已经过时了。

PHP的

评论


答:

2赞 Mike C 10/29/2010 #1

如果需要能够从密钥重新创建对象,则可以用作密钥。要重新创建对象,请调用 。serialize($obj)unserialize

1赞 mario 10/30/2010 #2

仍然没有找到原版,但记住了实际的技巧,所以我重新实现了它:
(我的互联网连接昨天关闭了,给了我时间)

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);
    }
}

它基本上是 ArrayAccess 和键的贬低数组和一个值的贬低数组。非常基本,但它允许:

$x = new FancyArray();

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

print $x[new SplFileInfo("x")];    // well, if set beforehand
2赞 salathe 10/30/2010 #3

听起来你想要重新发现 SplObjectStorage 类,它可以提供从对象到其他数据(在本例中为其他对象)的映射。

它实现了 ArrayAccess 接口,因此您甚至可以使用所需的语法,例如 .$store[$obj_a] = $obj_b