有一个像这样的示例类:
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
被针对?
您不能使用当前的实现。为了使其工作,您必须创建一个数组对象(即:一个实现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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)