Reputation: 33697
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.
Upvotes: 18
Views: 14008
Reputation: 3007
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.
Upvotes: 1
Reputation: 522382
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.
Upvotes: 26
Reputation: 9042
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.
Upvotes: -3