我正在学习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