【问题标题】:How to call parent constructor when a object is instantiated?实例化对象时如何调用父构造函数?
【发布时间】:2013-11-05 20:58:18
【问题描述】:

我有这个超类:

Class BaseController{
      public function __construct(){
          $this->view = new BaseView();
      }
}

我有 3 个扩展它的类。如何运行基类的构造函数,而不必将parent::__construct(); 放入子类的每个构造函数中?

【问题讨论】:

  • 你不能......一个子类方法覆盖父类的方法,除非你明确地调用它......或者不为你的子类定义一个 __construct() 方法

标签: php inheritance constructor


【解决方案1】:

如果您需要子构造函数,这是不可能的,如 php.net 文档所述。

http://php.net/manual/en/language.oop5.decon.php

注意:如果子类不隐式调用父构造函数 定义了一个构造函数。为了运行父构造函数,调用 子构造函数中的 parent::__construct() 是必需的。如果 child 没有定义构造函数,那么它可以从 父类就像一个普通的类方法(如果它没有被声明 作为私人)。

【讨论】:

    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 2021-11-22
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多