4

使用这样的示例类:

class Test{
    public function &__get($name){
        print_r($name);
    }
}

的一个实例Test将像这样回退输出:

$myTest = new Test;
$myTest->foo['bar']['hello'] = 'world';
//outputs only foo

有没有一种方法可以获取有关正在访问的数组的哪个维度的更多信息,向我展示(来自上一个示例)的bar元素foo和 的hello元素bar是目标?

4

3 回答 3

3

您不能使用当前的实现。为了使其工作,您必须创建一个数组对象(即:实现的对象ArrayAccess)。就像是:

class SuperArray implements ArrayAccess {
    protected $_data = array();
    protected $_parents = array();

    public function __construct(array $data, array $parents = array()) {
        $this->_parents = $parents;
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $value = new SuperArray($value, array_merge($this->_parents, array($key)));
            }
            $this[$key] = $value;
        }
    }

    public function offsetGet($offset) {
        if (!empty($this->_parents)) echo "['".implode("']['", $this->_parents)."']";
        echo "['$offset'] is being accessed\n";
        return $this->_data[$offset];
    } 

    public function offsetSet($offset, $value) {
        if ($offset === '') $this->_data[] = $value;
        else $this->_data[$offset] = $value;
    } 

    public function offsetUnset($offset) {
        unset($this->_data[$offset]);
    } 

    public function offsetExists($offset) {
        return isset($this->_data[$offset]);
    } 
}

class Test{
    protected $foo;

    public function __construct() {
        $array['bar']['hello'] = 'world';
        $this->foo = new SuperArray($array); 
    }

    public function __get($name){
        echo $name.' is being accessed.'.PHP_EOL;
        return $this->$name;
    }
}

$test = new Test;
echo $test->foo['bar']['hello'];

应该输出:

foo is being accessed.
['bar'] is being accessed
['bar']['hello'] is being accessed
world
于 2010-12-24T16:30:05.057 回答
1

不,你不能。 $myTest->foo['bar']['hello'] = 'world';通过以下翻译 $myTest->__get('foo')['bar']['hello'] = 'world';将它们部分分解为

$tmp = $myTest->__get('foo')
$tmp['bar']['hello'] = 'world';

您可以做的是创建一个ArrayAccess派生对象。在哪里定义自己的offsetSet()并从中返回__get()

于 2010-12-24T16:15:23.270 回答
1

您可以返回一个实现ArrayAccess的对象,而不是返回一个数组。对象总是通过引用返回和传递。这至少在水平上推动了问题。

于 2010-12-24T16:18:16.593 回答