【问题标题】:extending class with private constructor in php different from version 5.1 to 5.4在 php 中使用私有构造函数扩展类,不同于 5.1 到 5.4 版本
【发布时间】:2014-05-15 21:15:50
【问题描述】:

我有一个带有私有构造函数的类,以防止直接实例化。

class MyClass {

    private static $instance;

    private function __construct() {

    }

    public static function getInstance() {
        if (isset(self::$instance)) {
            return self::$instance;
        } else {
            $c = __CLASS__;
            self::$instance = new $c;
            return self::$instance;
        }
    }

}

我扩展它

class ExtendedClass Extends MyClass {
    //cannot touch parent::$instance, since it's private, so must overwrite
    private static $instance;
    //calling parent::getInstance() would instantiate the parent, 
    //not the extension, so must overwrite that too
    public static function getInstance() {
        if (isset(self::$instance)) {
            return self::$instance;
        } else {
            $c = __CLASS__;
            self::$instance = new $c;
            return self::$instance;
        }
    }
}

当我打电话时

$myInstance=ExtendedClass::getInstance();

在 PHP 5.4.5 中我得到

PHP 致命错误:从上下文调用私有 MyClass::__construct() '扩展类'

但在 PHP 5.1.6 中,一切正常

这里发生了什么?

另外:我没有写MyClass,我没有能力保护构造函数,如果我这样做会解决问题,但我不能。

【问题讨论】:

  • 你为什么不让你的父构造函数受保护而不是私有?
  • 我不能! MyClass 不是我真正写的,我没有能力修改它。

标签: php class oop inheritance extend


【解决方案1】:

它是the bug。你可以像这样修复你的代码(PHP > PHP5.3):

class MyClass {

    private static $instance;

    private function __construct() {

    }

    static function getInstance() {
        if (isset(self::$instance)) {
            return self::$instance;
        } else {
            self::$instance = new static();
            return self::$instance;
        }
    }

}


class ExtendedClass Extends MyClass {
}

【讨论】:

  • 查找错误文档的方法!优秀!谢谢!
  • 静态分析器会用Unsafe usage of new static() 抱怨这段代码(恕我直言,这是正确的,因为new static() 会导致难以发现的错误)。要解决此问题,您还应该使用final 标记私有构造函数,以便它不能被覆盖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多