Single legacy

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 to other classes that should be single-point. The problem is that the superclass makes an instance by itself, not a subclass. Any idea how I can get Superclass to instantiate a 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; } } 
+3
source share
2 answers

This is a limitation of PHP - the parent class cannot determine the name of the subclass on which its methods are statically called.

PHP 5.3 now supports late static bindings that will allow you to do what you need, but it will be some time before it is widely available. See info here

There are some similar questions here that might be worth reading for possible workarounds, like this one .

+4
source

The static method is bound to its defining type, and not to the instance. Classes for children do not inherit static methods (this does not make sense). They are still attached to the parent type. Thus, the GET method bound to the parent type will not be able to determine which type of subtype you just want to get. I am afraid that each child class will just have to implement its own GET method.

+1
source

All Articles