As in PHP 5.3.3, I tested this with 5.6 and 7.0, declaring that the __construct method of the final class would prevent any child class overriding the constructor, either using __construct or the PHP 4 style ClassName() (note that the PHP style 4 deprecated since PHP 7). Preventing the child class declaring the constructor ensures that the parent constructor is always called. This, of course, will not allow child classes to implement their own design logic. There will certainly be practical examples of use for this, although I would not recommend it as a good practice in general.
Some examples:
Without announcement __construct final
class ParentClassWithoutFinal { private $value = "default"; public function __construct() { $this->value = static::class; } function __toString() { return $this->value; } } class ChildClassA extends ParentClassWithoutFinal { public function __construct() {
With the final __construct
class ParentClassWithFinal extends ParentClassWithoutFinal { public final function __construct() { parent::__construct(); } } class ChildClassB extends ParentClassWithFinal { } echo (new ChildClassB());
Trying to declare __construct in a child class
class ChildClassC extends ParentClassWithFinal { public function __construct() { } }
Attempting to declare a ClassName() constructor in a child class
class ChildClassD extends ParentClassWithFinal { public function ChildClassD() { } }
bstoney
source share