The singleton is explained here: http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5. I want to use the singleton class as a superclass, and extend it in other classes that are supposed to be singletons. The problem is, the superclass makes an instance of itself, not the subclass. Any idea how I can make the Superclass create an instance of the Subclass?
class Singleton { // object instance private static $instance; protected function __construct() { } public function __clone() { } public function __wakeup() { } protected static function getInstance() { if (!self::$instance instanceof self) { self::$instance = new self; if(self::$instance instanceof Singleton) echo 'made Singleton object<br />'; if(self::$instance instanceof Text) echo 'made Test object<br />'; } return self::$instance; } } class Test extends Singleton { private static $values=array(); protected function load(){ $this->values['a-value'] = 'test'; } public static function get($arg){ if(count(self::getInstance()->values)===0) self::getInstance()->load(); if(isset(self::getInstance()->values[$arg])) return self::getInstance()->values[$arg]; return false; } }
This is a limitation of PHP – a parent class cannot determine the name of a subclass on which its methods are statically called.
PHP 5.3 now has support for late static bindings, which will let you do what you need to, but it will be a while before that is widely available. See some information here
There are several similar questions on here which might be worth reading for possible workarounds, for example this one