I have this code running on PHP 5.2.6
class Singleton { static private $instance = false; private $id = false; protected function __construct() { $this->id = uniqid(); } static public function instance() { if (!self :: $instance) { self :: $instance = new self(); } return self :: $instance; } public function get_id() { return $this->id; } } class Chucknorris extends Singleton { } echo "php version = ".phpversion()."<br>"; $singleton = Singleton::instance(); echo get_class($singleton)."<br>"; echo "singleton id = ".$singleton->get_id()."<br>"; $chucknorris = Chucknorris::instance(); echo get_class($chucknorris)."<br>"; echo "chucknorris id = ".$chucknorris->get_id()."<br>"; Here's the output
php version = 5.2.6 Singleton singleton id = 4ea7dca7d8f23 Singleton chucknorris id = 4ea7dca7d8f23 When I ask for an instance of Chucknorris, I always get the Singleton one. I'd like to find out a way to extend the Singleton.
I know we can use get_called_class method to do it but it comes only with PHP 5.3. Is there anyway I can extend a Singleton without redefining the design pattern in the extended classes ?