duanchi6397 2019-02-06 07:06
浏览 129

子类函数调用父类构造函数两次

I have 2 classes named C and P as follow:

<?php 
class P{
    var $a;
    function __construct(){
        echo "hello";
    }
    function func($a){
        echo "parent";
    }   
}
class C extends P{
    function func($a){
        echo "child";
    }
    function callpar(){
        parent::__construct();
    }
}
$obj=new C;
$obj->callpar();
?>

Why my output showing hello two times? I just want to call parent class construct for one time.

  • 写回答

1条回答 默认 最新

  • drxnfdx798517235 2019-02-06 15:39
    关注

    Parent constructor should only be called from the child constructor.

    If a child class doesn't have it's own constructor, the parent constructor is called automatically (like in your case).

    If a child class does have it's own constructor and does not call the parent constructor inside, a warning is shown Parent Constructor is Not Called. You must explicitly call the parent constructor in the child constructor. Some languages do this implicitly (like C#), but PHP doesn't. Java even forces you to call the parent constructor in the first line of the child constructor.

    Take a look at these 2 examples below:

    class P {
        function __construct() {
            echo 'P';
        }
    }
    class C extends P {
    // this child class doesn't have it's own constructor, so the parent constructor is called automatically
    }
    class D extends P {
        // this class has it's own constructor, so you must explicitly call the parent constructor inside of it
        function __construct() {
            parent::__construct();
            echo 'D';
        }
    }
    
    $c = new C; // outputs P
    $d = new D; // outputs PD
    
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题