通过引用使用__get()

时间:2010-12-24 16:00:24

标签: php properties get overloading magic-methods

使用如下示例类:

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

Test的实例会反复输出:

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

有没有办法可以获得有关正在访问的数组维度的更多信息,向我(从前面的示例)显示bar的{​​{1}}元素和{{1 } foo的元素正在被定位?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

不,你不能。 $myTest->foo['bar']['hello'] = 'world';进行以下翻译 $myTest->__get('foo')['bar']['hello'] = 'world';部分打破它们

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

您可以做的是创建ArrayAccess派生对象。您定义自己的offsetSet()并从__get()

返回的位置

答案 2 :(得分:1)

您可以返回实现ArrayAccess的对象,而不是返回数组。始终返回对象并通过引用传递。这至少会降低问题的推动力。