为什么“严格标准”不适用于PHP构造函数?

参见英文答案 > Why does PHP allow “incompatible” constructors?                                    5个
在现代版本的PHP(下面的5.6)中,以下是无效的程序

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将拒绝运行此命令,而是提供如下错误消息

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

从严格的角度来看,这是一件好事.但是,如果您使用构造函数尝试相同的事情

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

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

PHP没有问题,并将运行该程序.

有谁知道为什么严格标准不适用于构造函数的历史和/或技术背景?

解决方法:

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).

也:

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.

如果在所有扩展类上都需要相同的构造函数签名,那么继承的有用性将基本上被破坏.你能想象在应用程序的每个控制器上需要相同的构造函数签名吗?

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...