If I have a parent class that is extended by lots and lots of other classes, and I want to make sure the parent class's constructor is ALWAYS run, is it a bad idea to declare the constructor final
?
I was thinking of doing something like this:
class ParentClass {
public final function __construct() {
//parent class initialization...
$this->construct();
}
protected function init() {
echo 'constructing<br>';
}
}
class ChildClass extends ParentClass {
protected function init() {
//child class initialization
echo 'constructing child<br>';
}
}
that way the child class can have a sort-of constructor, and the parent class's constructor will always execute. Is this bad practice?
Declaring a final
__construct
ensures that no one who extends your class can implement a method with the same name. On the surface of it, this would seem like it would mean no one else can declare a constructor for sub-classes of this class, but this is not true, since the PHP 4 style of ClassName()
still works just fine as an alternate name for the constructor. So really, declaring a constructor as final gets you nothing in PHP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With