PHP quiz #5 - constructor overridingJune 16, 2019
Most PHP developers probably have already used constructor overriding, as it would be virtually impossible to create object oriented applications without it. Still, many of them might not be familiar with the exact rules around the subject - I know I wasn't.
What will this code output?
- A Warning: Declaration of B::__construct(Exception $e) should be compatible with A::__construct(LogicException $l)
- C Fatal error: Uncaught Exception: Exception!
AnswerShow the answer
In PHP, the only rule to overriding constructors is that there are no rules!
Constructors can be overridden with any signature. Their parameters can be changed freely and without consequence.
They can be overridden with completely unrelated parameter types:
Parameters can also be omitted (or added):
Note that this kind of freedom only applies to constructors. Were these functions not constructors, PHP would issue a warning:
This post was inspired by an inaccurate Wikipedia article.
This post is part of a series based on a presentation I gave on March 20, 2019.