get中 $this->Name 用不了
class Test{
private $aa=1;
function __get($proName){
return $this->proName;
}
}
$test=new Test();
echo $test->aa;
class Test{
private $aa=1;
function __get($proName){
return $this->proName;
}
}
$test=new Test();
echo $test->aa;
2015-11-11
舉報
2015-11-11
樓上錯解。
$this->proName; 其實就是在訪問對象的proName屬性,但是這個屬性是不存在的,所以肯定報錯。
你一定是覺得proName會被替換成$proName的值吧。
你肯定納悶過為什么類的屬性在定義的時候要$,如$aa,但訪問的時候卻不需要,如$this->aa;
原因就在于此,為了避免歧義。
__get的真正用法是這樣的:
class?Demo{ ????private?$pro?=?array(); ????public?__set($name,?$value){ ????????$this->pro[$name]?=?$value; ????} ???? ????public?__get($name){ ????????if(isset($this->pro[$name])){ ????????????return?isset($this->pro[$name]; ????????} ????????return?null; ????} }有什么不懂得去看手冊吧,PHP的手冊是最詳細的。
2015-11-11
少了個美元符
<?php class?Test { ????private?$aa?=?1; ???? ????public?function?__get($proName) ????{ ????????return?$this->$proName; ????} } $test?=?new?Test(); echo?$test->aa;