note 75862 deleted from function.get-class by peehaa

From: Date: Tue, 29 Nov 2016 10:26:43 +0000
Subject: note 75862 deleted from function.get-class by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-207737@lists.php.net to get a copy of this message
Note Submitter: Bryan ---- janci's Singleton example is all well and good, until you create another class "Bar" which also extends Singleton. <?php $single_foo = Foo::getInstance(); $single_bar = Bar::getInstance(); ?> $single_bar will now be an instance of Foo! This is because there is only one copy of the static variable $__instance in the Singleton class. Here is a better Singleton class: <?php abstract class Singleton { static $_instances = array(); //Prevent singletons from being instantiated other than via getInstance(); protected function __construct() {} protected function __clone() {} static function getInstance($class_name) { if(!isset(self::$_instances[$class_name])) { self::$_instances[$class_name] = new $class_name(); } return self::$_instances[$class_name]; } }?> Unfortunately, you are still required to define Foo as janci does. I would love to see an example where the only thing you add to the class is "extends Singleton" and you're done, but that seems to be impossible.

« previous php.notes (#207737) next »