首页 文章

在PHP中使用私有构造函数扩展类,不同于版本5.1到5.4

提问于
浏览
2

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

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致命错误:从上下文'ExtendedClass'调用私有MyClass :: __ construct()

但是在PHP 5.1.6中,一切都按预期工作

这里发生了什么?

Also: I did not write MyClass, I don't have the ability to make the constructor protected, If I did that would solve the problem, but I can't.

1 回答

  • 2

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

相关问题