加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如果子类没有定义构造函数,调用父构造函数?

发布时间:2020-12-13 14:04:11 所属栏目:PHP教程 来源:网络整理
导读:在 PHP Constructors and Destructors documentation它说 Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor,a call to parent::__construct() within the child const
在 PHP Constructors and Destructors documentation它说

Note: Parent constructors are not called implicitly if the child class
defines a constructor. In order to run a parent constructor,a call to
parent::__construct() within the child constructor is required.

但是,如果子类不调用构造函数,父构造函数是否仍然被调用?还是应该创建一个调用父构造函数的构造函数?

IE:

class BaseClass {
   function __construct() {
       print "In BaseClass constructorn";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
   }
}
也许这是一个很明显的,但是一些环顾四周,直接回答这个问题令人惊讶的是不是很容易找到,所以这里是:

如果子类没有定义构造函数,那么父构造函数将被调用.

在下面的示例中,$obj仍将从BaseClass调用构造函数,因为SubClass从未调用构造函数.

class BaseClass {
    function __construct() {
       print "In BaseClass constructorn";
    }
}

class SubClass extends BaseClass {
    //I do not have a constructor :(
}

$obj = new SubClass();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读