2011-12-08 40 views
0

我有下面的__set方法,它沒有被解僱。請注意方法頂部的echo '__set'。當我打電話$class->__set(...);而不是當我$class->title='whatever'__set不叫

public function __set($name, $value){ 
     echo '__set'; 
     if($this->{$name}==$value) return; 
     switch($name){ 
      case 'title': 
      case 'body': 
      case 'template': 
      case 'date': 
      case 'pageType': 
       if(!$this->exists()){ 
        $this->DB->insert('posts', array($name, $value)); 
        $this->ID=($this->DB->autoIncrement('posts')-1)<1?1:($this->DB->autoIncrement('posts')-1); 
       } 
       else{ 
        $this->DB->update('posts', array($name => $value)); 
       } 
       $this->{"$name"}=$value; 
       return; 
      break; 
     } 
     $this->{$name}=$value; 
    } 

的方法工作正常。希望只是一個小錯或類似的東西,但在最近15分鐘內沒有發現它。

+3

你有一個叫做$ title的屬性嗎?如果是這樣,那麼我很確定__set不會被調用。 – liquorvicar

+5

僅當您試圖分配值的屬性不存在或無法訪問時,纔會調用__set。你確定你的班級沒有公共$ title屬性嗎? – rdlowrey

回答

4

如果你正在運行到名稱衝突像在評論你的問題中提到的,你可以改爲實現與__set __get()()來完成你正在試圖做的,像這樣的:

class MyMagicClass 
{ 
    protected $vals = array(); 

    public function __get($name) 
    { 
    if (isset($this->vals[$name])) { 
     return $this->vals[$name]; 
    } 
    throw new OutOfBoundsException("$name is not a valid property"); 
    } 

    public function __set($name, $value) 
    { 
    $this->vals[$name] = $value; 
    // do your other stuff here ... 
    } 
} 

__get(),如__set(),僅在請求的對象屬性不存在或不可訪問(受保護/專用)時才被調用。如果按照上述示例進行操作,則所有「魔術」對象屬性都將存儲在受保護的$vals陣列中,並通過__get()__set()進行訪問。