普通网友 2011-01-17 10:35
浏览 186
已采纳

无法将构造函数定义为protected或private! 为什么?

--- A.php ----
require_once 'B.php';

class A
{
    public function __constructor($x){...}

    public function foo()
    {
        $b = B::getInstance();
        ...
    }
}

--- B.php ----
require_once 'A.php';

class B extends A
{
    protected static $_instance = null;

    protected function __construct(){}

    public static function getInstance()
    {....}
}

PHP just stops interpreting the code as soon as it reaches line

protected function __construct(){}

and outputs everything before and nothing that would have been sent to the browser afterwards.

And as soon as I just take that line out, by changing it to

// protected function __construct(){}

everything works fine!?

I don't get that.

Any ideas?

  • 写回答

3条回答 默认 最新

  • doushu2699 2011-01-17 10:41
    关注

    I've just created a simple test-file to confirm whether this happens on my machine too, and I think I've found the answer. Take the following code:

    <?php
    error_reporting( E_ALL | E_STRICT );
    class Foo {
        public function __construct( ) {
        }
    }
    
    class Bar extends Foo {
        protected function __construct( ) {
        }
    }
    

    When trying to execute that code, I get a fatal error: "PHP Fatal error: Access level to Bar::__construct() must be public (as in class Foo) in /home/berry/foo.php on line 12." That means you can't change the access level in a child class, if the parent has already defined the access level, which actually makes a lot of sense: PHP wouldn't know which constructor to call, I guess.

    As a side note: by looking at your code, B extends A, and A uses B. Why exactly is that so, it seems like a strange construction to me? I'm guessing you actually want is composition, not inheritance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000