This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.
PHP quiz #5 - constructor overridingJune 16, 2019
Okay! We have only seen weird edge cases so far. This one is actually pretty important.
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
PHP constructors can be overridden with any signature.
Their parameters can be changed freely and without consequence.
They can be overridden even if the parameter types are not related.
They can be overridden even if the number of parameters differ.
Were they not constructors, PHP would issue a warning.
This post was inspired by an inaccurate Wikipedia article.
I'm sure most PHP developers have already used constructor overriding, even if they didn't realize it. It's virtually impossible to create object oriented applications without it.
We'll take a look at overriding regular methods next.