php怎么用get取值,php – 通过引用使用__get()

使用如下示例类:

class Test{

public function &__get($name){

print_r($name);

}

}

Test的一个实例将反馈输出:

$myTest = new Test;

$myTest->foo['bar']['hello'] = 'world';

//outputs only foo

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

解决方法:

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

来源: https://codeday.me/bug/20190621/1256515.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值