5

In modern versions of PHP (5.6 below), the following is an 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 give you an error message like the following

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™ from a strictness point of view. However, if you try the same thing with a constructor function

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

class B extends A
{
    public function __construct()
    {
    }
}

PHP has no problem, and will run the program.

Does anyone know the history and/or technical context of why strict standard don't apply to constructors?

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • 1
    The only thing I found in the [manual](http://php.net/manual/en/language.oop5.decon.php) is: *Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.* – Rizier123 Jan 12 '16 at 19:20
  • 2
    I would guess that because the constructor is not been overloaded php doesn't care. When your try to use the constructor you would use new A() or new B() so theres is not conflict. But in the case you are trying to access a method php wouldn't know which one it should call because it only matches the function's name – Vinicius Zaramella Jan 12 '16 at 19:22

1 Answers1

4

From the PHP Manual:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Also:

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

The usefulness of inheritance would be essentially ruined if you required the same constructor signature on all extended classes. Can you imagine requiring the same constructor signature on every controller in an application?

Ben Harold
  • 6,242
  • 6
  • 47
  • 71