thinkphp __set __get方法使未知數組成員屬性賦值失敗

分類: php,thinkphp,thinkphp 發布時間: 2017-04-13 15:04 瀏覽: 1,341 次

<?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];
 }

如果覺得我的文章對您有用,請隨意打賞。您的支持將鼓勵我繼續創作!

天下蓝月亮资料精选大全