参见英文答案 > 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 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没有问题,并将运行该程序.
有谁知道为什么严格标准不适用于构造函数的历史和/或技术背景?
解决方法:
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.
如果在所有扩展类上都需要相同的构造函数签名,那么继承的有用性将基本上被破坏.你能想象在应用程序的每个控制器上需要相同的构造函数签名吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。