Why don't Strict Standards apply to PHP constructors?

In modern versions of PHP (5.6 below), the following invalid program

error_reporting(E_ALL); class A { public function hello(X $one, Y $two) { } } class B extends A { public function hello() { } } interface X { } interface Y { } $b = new B; 

PHP will refuse to run this and instead you will get the following error message

 PHP Strict standards: Declaration of B::hello() should be compatible with A::hello(X $one, Y $two) in test.php on line 15 Strict standards: Declaration of B::hello() should be compatible with A::hello(X $one, Y $two) in test.php on line 15 

This is a good thing in terms of rigor. However, if you try the same thing using the constructor function

 class A { public function __construct(X $one, Y $two) { } } class B extends A { public function __construct() { } } 

PHP has no problems and the program will start.

Does anyone know the history and / or technical context of why a strict standard does not apply to constructors?

+5
source share
1 answer

From the PHP Manual :

Note. Parent constructors are not called implicitly if the child class defines the constructor. To start the parent constructor, you need to call parent :: __ construct () in the child constructor. If the child does not define a constructor, it can be inherited from the parent class as a method of the normal class (if it was not declared as private).

also:

Unlike other methods, PHP does not generate an error message of the E_STRICT level when __construct () is redefined with different parameters than the parent method __construct ().

The utility of inheritance will be essentially destroyed if you need the same constructor signature for all extended classes. Can you imagine that the same designer signature is required for each controller in the application?

+4
source

Source: https://habr.com/ru/post/1240471/


All Articles