我正在學習OO PHP,並且正在嘗試在子類中使用parent ::方法。我注意到我不得不使用「額外」返回爲父方法的輸出顯示。 有人可以解釋我爲什麼這是?爲什麼在調用父項時使用返回
請理解我正在使用一本書,這個例子似乎有點多餘。請隨身攜帶,因爲下面的代碼是新手...
這是我使用的代碼,並且在代碼中我發表了評論。
class ShopProduct {
public $productnumber;
public function __construct($productnumber) {
$this->productnumber = $productnumber;
}
public function getSummary(){
return $this->productnumber;
}
}
class BookProduct extends ShopProduct {
public function __construct($productnumber) {
parent::__construct($productnumber);
}
public function getSummary() {
return parent::getSummary(); // if i dont use return it doesnt work? why is that?
// parent::getSummary(); is not enough it seems.
}
}
$product = new BookProduct(11111);
echo $product->getSummary();
?>
好吧,如果你不這樣做與價值的東西,父類的方法返回,你能指望什麼?返回不會將任何內容打印到輸出緩衝區。所以你在擴展類中調用函數,但是,擴展類對該函數沒有任何作用。因爲你的子函數的返回優先於父函數。 – Ohgodwhy 2014-09-27 19:15:18
'getSummary()'應該返回一個值,在這種情況下它只返回'parent :: getSummary()'的值。你當然可以重寫孩子的'getSummary()'。 – 2014-09-27 19:16:11
我的代碼的最後一行使用方法和Echo的。爲此我期待着這個價值。在父類方法中,返回值,所以我期待它在child方法中繼承「return」--behaviour,因爲我從孩子調用父方法。如果有人可以用更多的詞彙來解釋這將是最有幫助的。 – rinserepeat 2014-09-27 19:18:20