2013-07-22 29 views
1
<?php 
class classname 
{ 
public $attribute; 
function __get($name) 
{ 
return 'here:'.$this->$name; 
} 
function __set ($name, $value) 
{ 
$this->$name = $value; 
} 
} 
$a = new classname(); 
$a->attribute = 5; 
echo $a->attribute; 

當我運行上面的腳本,它顯示:5不顯示預期的結果時,使用__get()在PHP

問:

echo $a->attribute;這行代碼將調用function __get($name),對不對?所以爲什麼不顯示:here:5

回答

1

神奇的__get和__set和__call是僅當屬性屬性或方法未定義或不能從調用作用域訪問時調用,或者未定義。

爲了使這項工作,你將不得不刪除公共引用屬性或使其保護或私人。

class classname 
{ 
    protected $attribute; 
    function __get($name) 
    { 
    return 'here:'.$this->$name; 
    } 
    function __set ($name, $value) 
    { 
    $this->$name = $value; 
    } 
} 
$a = new classname(); 
$a->attribute = 5; // calling __set 
echo $a->attribute; // calling __get 
2

您將該屬性標記爲公共屬性,因此該屬性可以從課外訪問。

__get()用於從讀取數據不可訪問的屬性

http://www.php.net/manual/en/language.oop5.overloading.php#object.get

如果要強制任意屬性,使__get和__set被調用,您可以在私人地圖藏匿其中:

class classname 
{ 
    private $vars = array(); 
    function __get($name) 
    { 
     return 'here:'.$this->vars[$name]; 
    } 
    function __set ($name, $value) 
    { 
     $this->vars[$name] = $value; 
    } 
} 
0

這裏'屬性'是公開的,所以__get()魔法方法不會被調用。

+0

這不提供問題的答案。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 –

+0

這裏要參考PHP官方手冊鏈接:http://www.php.net/manual/en/language.oop5.overloading.php#object.get – gameboy90