2013-05-09 99 views
5

我嘗試使用構造函數的父類名稱,並部分爲我工作。在子節點後自動調用父構造函數PHP

「達斯·維達法」

像構造函數,但從來沒有首先調用來電

「盧克·天行者構造」 ..

有人知道如何做它?

例如:

Darth.php

​​

Luke.php

include("Darth.php") 

class LukeSkywalker extends DarthVader{ 
public function __constructor(){ 
     echo "- He told me enough! He told me you killed him!\n" 
     $this->response(); 
    } 
} 

預期結果:

  • 歐比旺從來沒有告訴你發生了什麼,以你的父親。

  • 他告訴我夠了!他告訴我你殺了他!

  • 號我是你爸爸

我真的會如此,自動喜歡它。

+2

嘿,現在 - 劇透! :D – andrewsi 2013-05-09 19:21:16

+0

我找到了「盧克天行者構造函數」沒有運行的原因。只是。是「__construc」,而不是「__constructor」,這支持@Marc B的理論。謝謝你們 – iLevi 2013-05-09 22:25:47

回答

20

按照文檔:http://php.net/manual/en/language.oop5.decon.php

注:父構造函數不如果子類定義了一個構造函數,則隱式調用。爲了運行父構造函數,需要在子構造函數中調用parent :: __ construct()。如果孩子沒有定義一個構造函數,那麼它可能像父類一樣繼承父類(如果它沒有被聲明爲私有的)。

2

默認情況下,父構造函數從不自動調用(除非在子類中定義)。即使在Java中,您也必須明確地調用它們,它必須是第一條語句。

請注意,在PHP中,構造函數的名稱是__construct,它應該是一個神奇的方法,因爲它是在創建對象時調用的。

class LukeSkywalker extends DarthVader{ 
    public function __construct(){ //See the name of magic method. It is __construct 
    parent::__construct(); //Call parents constructor 
    echo "- He told me enough! He told me you killed him!\n" 
    $this->response(); 
    } 
} 

使用上面的代碼,並在每次執行時,你會得到期望的結果:

new LukeSkywalker();

+8

除了默認情況下,他們被自動調用,除非他們是在孩子中定義的。 – Frug 2014-01-14 20:50:45

相關問題