thinkphp __set __get方法使未知数组成员属性赋值失败

分类: php,thinkphp,thinkphp 发布时间: 2017-04-13 15:04 浏览: 697 次

<?php

class pa{
 var $var = array();
 public function __get($name){
 echo "__get ".$name."<br>";
 return $this->var[$name];
 }
 public function __set($name,$val){
 echo "__set ".$name." {$val}<br>";
 $this->var[$name] = $val;
 }
}

class a extends pa{
 function a(){
 $this->aa = array('aaa'=>array('onchannel'=>array('request'=>'dsfds')));
 }
 function set(){
 //$this->aa['aaa'][] = 'sdf';
 //foreach ($this->aa as $key => $value) {

//}
$this->aa['aaa']['onchannel']['aa'] = 'sdfsdfasdas';
 var_dump($this->aa);
 }
}

$aa = new a();
$aa->set();

上面代码在运行”$this->aa['aaa']['onchannel']['aa'] = ‘sdfsdfasdas’;”这行代码时会出现如下php警告:

Notice: Indirect modification of overloaded property a::$aa has no effect

意思就是此次赋值无效。thinkphp里也定义了这两个魔术方法,如果你想做这种类似的操作,要先定义好成员属性,避免触发到__get,__set方法,因为__get返回的是一个临时变量;或在__get前加&,如下:

public function &__get($name){
 echo "__get ".$name."<br>";
 return $this->var[$name];
 }

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!