Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do "Strict Standards" not Apply to PHP constructors? [duplicate]

Tags:

oop

php

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?

like image 562
Alan Storm Avatar asked Sep 25 '22 16:09

Alan Storm


1 Answers

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?

like image 53
Ben Harold Avatar answered Oct 11 '22 12:10

Ben Harold