2012-06-08 67 views
1

我對PHP的面向對象系統和小怪癖有點新鮮。從我讀過的__get和__set方法在訪問不可訪問的字段時被調用。所以,顯然訪問類中的公共字段或受保護的字段將不會調用這些函數。但是如果我嘗試訪問$ obj-> a並且以前從未定義過一個呢?我原本以爲這會調用__get或__set,但它似乎沒有。我知道解決這個問題的方法是將所有動態創建的字段放入數據數組中。PHP magic __get和__set。動態創建的字段被認爲是「可訪問的」?

是$ obj->因此是一個公共領域?非常感謝你!

class Example 
    { 
    public function __get($field) 
    { 
     echo 'Getting ' . $field; 
     return $this->$field; 
    } 

    public function __set($field, $value) 
    { 
     echo 'Setting ' . $field . ' to ' . $value; 
     $this->$field = $value; 
    } 
    } 

    $obj = new Example; 
    $obj->randomField = 1; //here randomField is set to 1 but the echo statement is not printed out in __set 
    echo $obj->randomField; //here, 1 will be echoed but not the statement in __get 

    //is randomField a public field? 
+0

在'__set'將被打印出來,是什麼問題的回聲? – xdazz

+0

「是$ obj->因此是公共領域嗎?」是的,正如您的示例所示... – Matthew

+0

我從經驗中知道「動態」屬性具有公開可見性,但我徒勞地搜索了PHP手冊中的引用。 –

回答

3
$obj = new Example; 
$obj->randomField = 1; // here __set method is called 
echo $obj->randomField; // here __get method won't be called because `$obj->randomField` exists. 

//is randomField a public field? 
// Yes, after you set it, it became a public field of the object. 
相關問題