2014-06-05 71 views
0

我正在構建一個類,最初想重載構造,但發現這在PHP中是不允許的。我的解決方案是使用一個構造函數的可變參數。但是,我有一些問題在鍵=值對中使用字符串文字並分配類屬性。這導致我問我的主要問題 - 是否可以通過構造函數使用變量來分配類屬性?是否可以使用變量變量來動態分配類屬性,以便允許PHP中具有可變參數的類構造函數?

見下面的例子:

class funrun{ 

    protected $run_id; 
    protected $fun_id; 
    protected $funrun_title; 
    protected $date; 

    function __construct(){ 

    if (func_num_args() > 0){ 
     $args = func_get_args(0); 
     foreach($args as $key => $value){ 
      $this->$key = $value; 
     } 

    $this->date = date(); 

    function __get($name){ 
     return $this->name; 
    } 

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

} 

這似乎正確分配的值。但後來,當我做到以下幾點:

$settings = array ('run_id' => 5, 'fun_id' => 3); 
$fun_example = new funrun($settings); 
echo $fun_example->run_id; 

我得到一個錯誤的getter方法不能正常工作:

Undefined property: funrun::$name 

然而,當我的類碼開關被$ this->鍵,類屬性似乎根本沒有分配。當我做$ fun_example - > $ run_id時,不會返回任何內容。

我在這裏錯過了什麼?反正有用字符串文字分配類屬性的數組嗎?如果不是,用構造函數解決可變參數問題的好方法是什麼?

+0

你爲什麼聲明爲保護所有的屬性,然後提供魔術方法,使您能夠訪問它們,好像他們是公衆?爲什麼不直接宣佈它們是公開的呢? – Barmar

回答

1

$this->name正在尋找名爲name的房源。變量屬性被寫爲:

$this->$name 

查看段落開頭類屬性也可以使用可變屬性名訪問。在PHP文檔variable variables

您的構造函數被錯誤地編寫。它遍歷參數列表,期望它是一個關聯數組。但是您將設置作爲單個參數傳遞。因此,它應該是:

function __construct($args) { 
    foreach ($args as $key => $value) { 
     $this->$key = $value; 
    } 
    $this->date = time(); 
} 
+0

嗯巴爾馬,我試過這樣做,雖然屬性已設置,但我無法通過執行$ fun_example-> run_id來訪問該變量。 PHP 5.4甚至支持使用$ this的變量變量嗎? [見這裏:http://www.php.net/manual/en/language.variables.variable.php]。謝謝! – snehoozle

+0

請參閱我更新的答案中的更正的構造函數。 – Barmar

+0

謝謝Barmar。現在工作。認爲我在訪問類屬性和變量屬性之間感到困惑,完全沒有意識到我的get和set方法需要使用變量屬性表示法。 – snehoozle

相關問題