How to subclass Singleton in PHP?

I am trying to subclass a class that uses a singleton pattern and populates an instance with a subclass.

I seem to have some minor issues.

class Singleton { static private $instance; static public function instance(){ if(is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } private function __construct(){} } class MySingleton extends Singleton { } echo get_class(MySingleton::instance()); //=> Singleton //=> I'm hoping to see MySingleton 
+6
source share
3 answers

What you are looking for is late static binding , which is a new PHP 5.3 feature. Try replacing new self() with new static() , and this should work for you.

self always refers to the contained class, while static refers to the "called" class.

+8
source

Your base singleton class prevents this from happening. if you change the code to this, it will work.

 <?php class Singleton { static private $instances = array(); static public function instance(){ $class = get_called_class(); if(!isset(self::$instances[$class])){ self::$instances[$class] = new $class(); } return self::$instances[$class]; } private function __construct(){} } class MySingleton extends Singleton { } echo get_class(MySingleton::instance()); //=> MySingleton 

Now it works because Singleton allows one instance for a child class.

+1
source

it works

 <?php class Singleton { static private $instance; static public function instance(){ static $instance = null; return $instance ?: $instance = new static; } public function __construct(){} } class MySingleton extends Singleton { } 

But I recommend the following:

 <?php class Singleton { static protected $instance; //should not be private static public function instance(){ if(is_null(static::$instance)){ static::$instance = new static(); } return static::$instance; } public function __construct(){} } class MySingleton extends Singleton { static protected $instance; //must explicitly declared } 
0
source

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


All Articles