How to create an instance of a child singleton abstract class?

I have an abstract class and a child that extends the abstract class. The child must be a sigleton. Here is a simplified example of an abstract class:

abstract class AbstractClass{
    protected static $instance = NULL;
    abstract protected function meInit();

    private function __construct(){
        $this->meInit();
        $this->init();
    }

    private function __clone(){}

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

    function init(){
        'code here;

    }
}

Here is a simplified child class:

class ChildClass_A extends AbstractClass{

    protected function meInit(){
        'some code;
    }
}

When I try to get an instance of a child $child = ChildClass_A::getInstance();, I get this error:

Fatal error: unable to create AbstractClass abstract class in C: \ wamp \ www \ Classes \ AbstractClass.php on line 7

I suspect that the culprit is in self::$instance=new self;. How do I redo it to achieve what I need?

+4
source share
1 answer

; new self(), , new A(). get_called_class(), B.

// ONLY SUPPORTS ONE SUBCLASS
// KEEP READING BELOW FOR COMPLETE SOLUTION
abstract class A {

    static protected $instance = null;

    abstract protected function __construct();

    static public function getInstance() {
        if (is_null(self::$instance)) {
            $class = get_called_class();
            self::$instance = new $class();
        }
        return self::$instance;
    }

}

class B extends A {
    protected function __construct() {
        echo "constructing B\n";
    }
}

var_dump(B::getInstance()); // constructing B, object(B)#1 (0) {}
var_dump(B::getInstance()); // object(B)#1 (0) {}

, , ?

class C extends A {
    protected function __construct() {
        echo "constructing C\n";
    }
}

var_dump(C::getInstance()); // object(B)#1 (0) {}
var_dump(C::getInstance()); // object(B)#1 (0) {}

, ! C, B ! , A . .

, !

// SOLUTION:
// WORKS FOR MULTIPLE SUBCLASSES
abstract class A {

    static protected $instances = array();

    abstract protected function __construct();

    static public function getInstance() {
        $class = get_called_class();
        if (! array_key_exists($class, self::$instances)) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }

}

B C ...

class B extends A {
    protected function __construct() {
        echo "constructing B\n";
    }
}

class C extends A {
    protected function __construct() {
        echo "constructing C\n";
    }
}

,

var_dump(B::getInstance()); // constructing B, object(B)#1 (0) {}
var_dump(B::getInstance()); // object(B)#1 (0) {}

var_dump(C::getInstance()); // constructing C, object(C)#2 (0) {}
var_dump(C::getInstance()); // object(C)#2 (0) {}

, ! , !

+7

Source: https://habr.com/ru/post/1589349/


All Articles