2010-03-18 110 views
3

我有一門課我在使用__set。因爲我不希望它設置任何東西,所以我有一個批准的變量數組,它會在它實際設置一個類屬性之前進行檢查。php:在某些情況下避免__get?

但是,在構造上,我想要__construct方法來設置幾個類屬性,其中一些屬性不在允許列表中。因此,當構建發生時,我做了$this->var = $value,我當然得到我的例外,我不允許設置該變量。

我能以某種方式解決這個問題嗎?

回答

4

聲明類成員:

class Blah 
{ 
    private $imAllowedToExist; // no exception thrown because __set() wont be called 
} 
1

聲明的類成員是你最好的選擇。如果這不起作用,你可以有一個開關($this->isInConstructor?)決定是否拋出錯誤。

在另一方面,你也可以使用__get方法還有__set方法,並同時擁有它們映射到一個包庫:

class Foo 
{ 
    private $library;   
    private $trustedValues; 

    public function __construct(array $values) 
    { 
     $this->trustedValues = array('foo', 'bar', 'baz'); 
     $this->library = new stdClass(); 
     foreach($values as $key=>$value) 
     { 
      $this->library->$key = $value; 
     } 
    } 

    public function __get($key) 
    { 
     return $this->library->$key; 
    } 

    public function __set($key, $value) 
    { 
     if(in_array($key, $this->trustedValues)) 
     { 
      $this->library->$key = $value; 
     } 
     else 
     { 
      throw new Exception("I don't understand $key => $value."); 
     } 
    } 
} 
相關問題