dongzhanlian6289 2014-09-27 19:13
浏览 15
已采纳

为什么在打电话给父母时使用退货?

I am learning OO PHP and I was experimenting with using a parent::method in a child class. I noticed i had to use an "extra" return for the output of the parent method to show up. Could someone explain me why this is?

This is the code I used and in the code I made a comment.

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();
?>
  • 写回答

1条回答 默认 最新

  • doukuipai8544 2014-09-27 19:23
    关注
    public function getSummary() {
        return parent::getSummary(); // if i dont use return it doesnt work? why is that?
        // parent::getSummary(); is not enough it seems.
    }
    

    Replace parent::getSummary() with any other function or method call:

    public function getSummary() {
        foo();
    }
    

    Of course you wouldn't expect getSummary to return anything in this case, right? Just because the method you're calling is parent::... doesn't change anything about this behaviour. It does not return automagically, because you may want to do something like this:

    public function getSummary() {
        $summary = parent::getSummary();
        return "Book: $summary";
    }
    

    BTW, if the only thing your method does is call its parent, you can leave out the entire method. In other words, this:

    class BookProduct extends ShopProduct {
    
        public function __construct($productnumber) {
            parent::__construct($productnumber);
        }
        public function getSummary() {
            return parent::getSummary();
        }
    }
    

    is exactly the same as this:

    class BookProduct extends ShopProduct { }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示