2013-07-24 23 views
5

我有這樣的代碼:我怎麼叫,其原有的參數父類的構造函數在PHP

class A { 
    var $arr = array(); 

    function __construct($para) { 
    echo 'Not called'; 
    } 
} 

class B extends A { 
    function __construct() { 
    $arr[] = 'new Item'; 
    } 
} 

而作爲B有它自己的構造結構($段)不會被調用。

現在我可以調用parent :: __結構($段),但是B類需要注意的參數A類需求。

我寧願這樣:

class A { 
    var $arr = array(); 

    function __construct($para) { 
    echo 'Not called'; 
    } 
} 

class B extends A { 
    function __construct() { 
    parent::__construct(); // With the parameters class B was created. 

    // Additional actions that do not need direct access to the parameters 
    $arr[] = 'new Item'; 
    } 
} 

將類似的東西的工作?

我不喜歡這樣一個事實,即所有擴展類A的類都需要定義一個新的構造方法,一旦類A改變了它的參數,我希望它們所做的就是調用類A的構造方法, B類不會用自己的__construct()方法覆蓋它。

回答

4

一個解決辦法是不重寫擺在首位的父類的構造。相反,請定義父構造函數自動調用的單獨(最初爲空)的方法。該方法可以在孩子中被覆蓋以執行額外的處理。

class A { 
    public function __construct($para) { 
     // parent processing using $para values 

     // ..and then run any extra child initialization 
     $this->init(); 
    } 
    protected function init() { 
    } 
} 

class B extends A { 
    protected function init() { 
     // Additional actions that do not need direct access to the parameters 
    } 
} 
+0

是的,這看起來像我正在尋找。謝謝! – JochenJung

+1

我一直在廣泛地在項目中使用這種方法,雖然它確實有效,但我從不喜歡它,因爲它稍微重新構造了構造函數。它會將您的對象變成某種Base對象,並妨礙重用。 – Gordon

5

有一種方法可以做到這一點幾乎完全一樣,你最初描述的那樣,通過使用call_user_func_array()func_get_args()功能:

class B extends A { 
    function __construct() { 
     // call the parent constructor with whatever parameters were provided 
     call_user_func_array(array('parent', '__construct'), func_get_args()); 

     // Additional actions that do not need direct access to the parameters 
     $arr[] = 'new Item'; 
    } 
} 

雖然它使一個有趣的練習,我個人實際上並不推薦使用這個 - 我認爲使用單獨的init()方法是一個更好的設計。

+0

我實際上比init()方法更喜歡這種方法,因爲它不會重新構造構造函數。 – Gordon

+0

這絕對是一種個人喜好。對於我自己,我不喜歡看到包含方法名稱的字符串 - 它有點過於'eval'ish,(IMO)PHP的弱點之一,以及[變量變量](http://php.net/manual /en/language.variables.variable.php)等。 – jcsanyi

相關問題