PHP quiz #5 - constructor overriding
June 16, 2019Most 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.
Question
What will this code output?
- A Warning: Declaration of B::__construct(Exception $e) should be compatible with A::__construct(LogicException $l)
-
B
B
-
C
AB
- C Fatal error: Uncaught Exception: Exception!
Answer
Show the answerB
Explanation
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):
Overriding functions
Note that this kind of freedom only applies to constructors. Were these functions not constructors, PHP would issue a warning:
Credits
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.
- PHP quiz #1 - for loop
- PHP quiz #2 - echo
- PHP quiz #3 - operator associativity
- PHP quiz #4 - hoisting
- PHP quiz #5 - constructor overriding
- PHP quiz #6 - covariance