php - 在 php 中使用私有(private)构造函数扩展类与版本 5.1 到 5.4 不同

标签 php class oop inheritance extend

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

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 Fatal error: Call to private MyClass::__construct() from context 'ExtendedClass'

但是在 PHP 5.1.6 中,一切都按预期运行

这里发生了什么?

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

最佳答案

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 {
}

关于php - 在 php 中使用私有(private)构造函数扩展类与版本 5.1 到 5.4 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847871/

相关文章:

PHP 音节检测

php - 获取 UL 标签的内容以发布到数据库

php - 为什么将有状态对象传递给构造函数是一件坏事?

c# - 我应该在 C#.net 中使用静态类进行数据库连接吗?

php - 使用 php 从 h1 标签获取所有值

python - 在多个 For 循环中追加到类列表

PHP 错误 : mysql_num_rows(): supplied argument is not a valid MySQL

JavaScript 字符串替换函数丢失类对象

c# - 您希望设计架构具备哪些品质,以便编码团队可以轻松实现?

php - DIV 元素未被其中的内容向下推