简体   繁体   English

PHP> 5.4:覆盖具有不同签名的构造函数

[英]PHP > 5.4: overriding constructor with different signature

We know that PHP doesn't accept child methods with a different signature than the parent . 我们知道PHP不接受具有与父代签名不同的签名的子方法。 I thought that was the same with constructors: The PHP documentation states that 我认为构造函数也是如此:PHP文档说明了这一点

This also applies to constructors as of PHP 5.4. 这也适用于PHP 5.4的构造函数。 Before 5.4 constructor signatures could differ. 在5.4构造函数签名可能不同之前。

However, it appears that inherited constructors still can differ in PHP versions > 5.4. 但是,似乎继承的构造函数仍然可以在PHP版本> 5.4中有所不同。 For example the following code does not trigger any warnings or notices: 例如,以下代码不会触发任何警告或通知:

class Something { }
class SomeOtherThing { }

class Foo
{
    public function __construct(Something $foo)
    {
    }

    public function yay()
    {
        echo 'yay';
    }
}

class Bar extends Foo
{
    public function __construct($foo, SomeOtherThing $bar = null)
    {
    }
}

$x = new Bar(new Something());
$x->yay();

According to the documentation, the code should trigger an error, as the contructor signatures are different. 根据文档,代码应该触发错误,因为构造函数签名不同。

Tried this on PHP 5.6.4. 在PHP 5.6.4上试过这个。 Same effect with other versions . 其他版本相同的效果。

So, what's up with that? 那么,那是什么呢? Are differing constructor signatures still legal, despite of what the documentation says? 尽管文档说的是什么,不同的构造函数签名仍然合法吗? Or is this a bug which will be fixed in later versions? 或者这是一个将在以后的版本中修复的错误?

According to the documentation 根据文件

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. 与其他方法不同,当使用与父__construct()方法不同的参数覆盖__construct()时,PHP不会生成E_STRICT级错误消息。

So, that is why you are not getting an error of level E_STRICT. 所以,这就是为什么你没有得到E_STRICT级别的错误。 Perhaps it will trigger something at a different level. 也许它会触发不同程度的东西。

I think you somewhat misread the documentation, because it states: 我认为你有点误读了文档,因为它指出:

Furthermore the signatures of the methods must match, ie the type hints and the number of required arguments must be the same. 此外,方法的签名必须匹配,即类型提示和所需参数的数量必须相同。 For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. 例如,如果子类定义了一个可选参数,而抽象方法的签名没有,则签名中不存在冲突。

You've defined an optional parameter, so it's ok. 你已经定义了一个可选参数,所以没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM