Must I call parent::__construct() in the first line of the constructor?

房东的猫 提交于 2021-02-07 11:53:26

问题


I know in Java, super() in a constructor has to be called as the first line of an overridden constructor.

Does this also apply to the parent::__construct() call in PHP?

I found myself writing an Exception class like this:

class MyException extends Exception {

  public function __construct($some_data) {

    $message = '';
    $message .= format_data($some_data);
    $message .= ' was passed but was not expected';

    parent::__construct($message);
  }

}

and I wondered if this would be considered an error/bad practice in PHP.


回答1:


If you want the code in the parent's constructor to be executed, you need to call parent::__construct(…) at some point. It does not technically matter when you do so. Sometimes it makes more sense to do a little work in the overridden constructor before calling the parent's constructor, sometimes you rely on work the parent's constructor does before you can do work in the overridden constructor.

As a rule of thumb I'd say you should call the parent's constructor as soon as possible. If you need to do something before you can call the parent's constructor, do so. If not, call it immediately. This is to avoid the parent's constructor undoing any of the work you're doing in the overridden constructor, like setting certain properties for example.

class A {
    function __construct() {
        $this->foo = 'bar';
    }
}

class B extends A {
    function __construct() {
        // parent::__construct();
        $this->foo = 'baz';
        // parent::__construct();
    }
}

In the above sample, the difference between calling the parent first or last makes a big difference in the resulting object. Which is more appropriate depends on what you're trying to do.




回答2:


The main question is not whether the call to the parent constructor it should be executed on the first line, or executed at all. Instead it's about what can be considered better practice and why.

Doubling the given answers: yes, you can omit parent::__construct altogether; yes, you can call it from wherever you like inside the __construct function of the child class. And any approach is good, as long as it makes sense and is consistent.

If you have a parent class with three children, for example, and every child uses the parent::__construct call in it's own way, then it can be a flag that the inheritence is not too clear and should be refactored.




回答3:


If you want to execute the code in the parent's constructor, then the answer is yes. If the child class overwrites the parent's constructor, you should omit it.



来源:https://stackoverflow.com/questions/39748226/must-i-call-parent-construct-in-the-first-line-of-the-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!