2014-01-27 27 views
0

如何將數據方法轉換爲該類的屬性?可能嗎?PHP類:如何使一個make方法的數據成爲類的屬性?

例如,下面的類article只有一個屬性 - $ VAR1,

class article 
{ 
    public $var1 = "var 1"; 
    public function __construct() 
    { 

    } 

    public function getRow() 
    { 
     $array = array(
      "article_id" => 1, 
      "url"  => "home", 
      "title"  => "Home", 
      "content" => "bla bla" 
     ); 

     return (object)$array; 
    } 
} 

得到$這種特性,

$article = new article(); 
print_r($article->var1); // var 1 

得到$這種方法,

$row = $article->getRow(); 

要得到$這個方法的數據,

print_r($row->title); // Home 

它正常工作,以這種方式,但如何,如果我想品牌/ **一個低於移動這個DAT到**類的屬性

  "article_id" => 1, 
      "url"  => "home", 
      "title"  => "Home", 
      "content" => "bla bla" 

這樣我就可以調用這樣的數據,

$article = new article(); 
print_r($article->title); // Home 

這可能嗎?

回答

1

您需要使用魔術__set()方法來創建不存在的屬性。如果你想保存當前的邏輯之後從移動的方法簡單屬性分配

class article 

{ 
    public $var1 = "var 1"; 
    public function __construct() 
    { 
     $this->getRow(); 
    } 

    public function getRow() 
    { 
     $this->article_id = 1; 
     $this->url = 'home'; 
     $this->title = "Home"; 
     $this->content = 'bla bla'; 
    } 

    public function __set($name, $value) { 
     $this->$name = $value; 
    } 
} 

$article = new article(); 
echo $article->title; // prints Home 

對象回報(你所說的舉動,但可以肯定,你不想打破你的getRow()邏輯),你可以在另一個方法中(或在構造函數中)移動賦值。

class article 

{ 
    public $var1 = "var 1"; 
    public function __construct() 
    { 
     foreach ($this->getRow() as $name => $value) { 
      $this->$name = $value; 
     } 
    } 

此外,如果你不不會有什麼不同,要神奇地使用從getRow()的屬性,你可以在你__set()方法去掉任何其他分配:

$rows = (array)$this->getRow(); 
if (!array_key_exists($name, $rows)) { 
    unset($this->$name); 
} 
+0

感謝您的回答! :D – laukok

1

一可能的方法是設置像這樣的屬性:

class article 
{ 
    public function __construct() 
    { 
     $array = array(
      "article_id" => 1, 
      "url"  => "home", 
      "title"  => "Home", 
      "content" => "bla bla" 
     ); 
    foreach($array as $key => $value){ 
     $this->{$key} = $value; 
     } 
    } 
} 

現在你可以得到:

$article = new article(); 
print_r($article->title); //Home 
+0

感謝您的幫助! :-) – laukok

相關問題