PHP > 5.4: 覆盖具有不同签名的构造函数
PHP > 5.4: overriding constructor with different signature
我们知道 PHP 不接受 different signature than the parent. I thought that was the same with constructors: The PHP documentation states
的子方法
This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.
但是,似乎继承的构造函数 仍然 在 PHP 版本 > 5.4 中可能有所不同。例如以下代码不会触发任何警告或通知:
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();
根据文档,代码应该触发错误,因为构造函数签名不同。
在 PHP 5.6.4 上试过这个。与 other versions.
效果相同
那么,这是怎么回事?不管文档怎么说,不同的构造函数签名是否仍然合法?或者这是一个会在以后的版本中修复的错误?
我认为您有点误读了文档,因为它指出:
Furthermore the signatures of the methods must match, i.e. 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.
你已经定义了一个可选参数,所以没问题。
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.
所以,这就是为什么您没有收到 E_STRICT 级错误的原因。也许它会触发不同层面的事情。
我们知道 PHP 不接受 different signature than the parent. I thought that was the same with constructors: The PHP documentation states
的子方法This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.
但是,似乎继承的构造函数 仍然 在 PHP 版本 > 5.4 中可能有所不同。例如以下代码不会触发任何警告或通知:
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();
根据文档,代码应该触发错误,因为构造函数签名不同。
在 PHP 5.6.4 上试过这个。与 other versions.
效果相同那么,这是怎么回事?不管文档怎么说,不同的构造函数签名是否仍然合法?或者这是一个会在以后的版本中修复的错误?
我认为您有点误读了文档,因为它指出:
Furthermore the signatures of the methods must match, i.e. 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.
你已经定义了一个可选参数,所以没问题。
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.
所以,这就是为什么您没有收到 E_STRICT 级错误的原因。也许它会触发不同层面的事情。