note 75862 added to function.get-class
| From: | Bryan at osu1 dot php dot net | Date: | Tue, 19 Jun 2007 15:07:21 +0000 |
| Subject: | note 75862 added to function.get-class | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-127789@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 64.71.164.2
Probable Submitter: 66.15.236.210
----
Manual Page -- http://www.php.net/manual/en/function.get-class.php
Edit -- https://master.php.net/note/edit/75862
Del: integrated -- https://master.php.net/note/delete/75862/integrated
Del: useless -- https://master.php.net/note/delete/75862/useless
Del: bad code -- https://master.php.net/note/delete/75862/bad+code
Del: spam -- https://master.php.net/note/delete/75862/spam
Del: non-english -- https://master.php.net/note/delete/75862/non-english
Del: in docs -- https://master.php.net/note/delete/75862/in+docs
Del: other reasons-- https://master.php.net/note/delete/75862
Reject -- https://master.php.net/note/reject/75862
Search -- https://master.php.net/manage/user-notes.php