2012-05-14 25 views
0

我有類PHP組數據

class User extends BaseModel{ 
    public $id; 
    public $name; 
} 

class BaseModel{ 
    function __construct($data=null){ 
      if($data!=null) 
      //set $id and $name 
    } 
} 

我想設置的$ id,$名稱和通過調用

$test = new User(array('id'=>1,'name'=>'user name')) 

擴展BaseModel任何其他數據我試圖用

$this->__set($arrayKey,$arrayValue); 

但我得到的錯誤:致命錯誤:調用未定義的方法,用戶:: __集() 我在做什麼錯? 謝謝你的幫助。

+0

可能重複[訪問對象,具有可變屬性?](http://stackoverflow.com/questions/7692162/access-object-attribute-with-variable) –

回答

0

通過數據只是環和分配每個屬性:

class BaseModel { 
    function __construct($data = NULL) { 
      foreach ((array) $data as $k => $v) { 
       $this->$k = $v; 
      } 
    } 
} 

沒有定義,你得到了錯誤約__set()的原因是因爲你沒有定義它。雖然__set()是一種神奇的方法,但如果您想對它做某些事情,您仍然必須定義它的行爲。

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

__set is run when writing data to inaccessible properties

這意味着,如果你試圖在你不能(如私有或受保護的變量)的作用域爲「設置」一類的變量,此功能將運行。

class Test { 
    private $var; 
} 

$c = new Test; 
$c->var = 1; // Error, or call __set if defined 
0
foreach ($data as $key => $value) { 
    $this->$key = $value; 
} 
+0

謝謝,這是更簡單了很多,然後我認爲這將是。 還有一件事,你能告訴我如何找出變量是否被聲明。當我使用isset時,它返回false,因爲變量是null,但它被聲明。 – somerandomusername

0

試試這個

class BaseModel{ 
    function __construct($data=null){ 
      if($data!=null) 
     { 
      //set $id and $name 
      $this->id = $data['id']; 
      $this->name = $data['name']; 
     } 
    } 
}