dongshan2004 2016-01-12 19:15
浏览 27

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

This question already has an answer here:

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?

</div>
  • 写回答

1条回答 默认 最新

  • dongzhong6675 2016-01-12 19:22
    关注

    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?

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题