tags:

views:

290

answers:

2
+2  Q: 

Singleton heritage

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;
    }
}
+1  A: 

A static method is tied to its defining type, not an instance. Child classes do not inherit static methods (that would make no sense). They are still tied to the parent type. Thus, the GET method, which is tied to the parent type, will not have a way to determine which kind of subtype you just wanted to get. I'm afraid that each child class will just have to implement its own GET method.

Vilx-
Actually, there's a hack called "late static binding", which is coming in 5.3, but that doesn't mean it's a good idea to use it.
troelskn
+3  A: 

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

Tom Haigh