gpt4 book ai didi

php - 通过引用使用 __get()

转载 作者:可可西里 更新时间:2023-10-31 22:59:18 27 4
gpt4 key购买 nike

使用这样的示例类:

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

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

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

有没有一种方法可以获得有关正在访问数组的哪个维度的更多信息,向我展示(从前面的示例中)foobar 元素, 和 barhello 元素被定位了?

最佳答案

您不能使用当前的实现。为了使其工作,您必须创建一个数组对象(即:一个实现 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

关于php - 通过引用使用 __get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4527175/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com