Search code examples
phpclassoopinheritanceextend

extending class with private constructor in php different from version 5.1 to 5.4


I have a class with a private constructor, to prevent direct instantiation.

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

}

I extend it

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

When I call

$myInstance=ExtendedClass::getInstance();

In PHP 5.4.5 I get

PHP Fatal error: Call to private MyClass::__construct() from context 'ExtendedClass'

But In PHP 5.1.6, everything works as expected

What is happening here?

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.


Solution

  • It is the bug. You could fix your code like this (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 {
    }