I’m learning PHP and found some surprising behaviour when I was trying to figure out why a constructor wasn’t getting called.
<?php
class Shape {
function __construct() {
echo 'Shape.';
}
}
class Triangle extends Shape {
function __construct() {
echo 'Triangle';
}
}
$tri = new Triangle();
?>
I’m used to java, so I thought this would output “Shape. Triangle.” Surprisingly, it just outputs “Triangle.” I searched for the problem and apparently I can kinda sorta fix it by putting parent::__construct(); in the child class, but that doesn’t seem ideal. Is there anything I can do to the Shape class to ensure that child classes always call the parent constructor? Do I really have to write parent::__construct(); in the class of every child whenever the parent has a constructor?
If you define a method of the same name in a child class, the parent’s method is overridden and will not be called under any circumstances, unless you do so explicitly. I.e.: No, there’s nothing you can do about it, you have to call
parent::__construct()explictly.