PHP function Singleton allows you holding exactly one object of a class in memory. If an object of a given class doesn't exist, Singleton will create and store a new one in static array singleton. It then (and otherwise) will return a reference to it.
Adding an optional ID allows holding more than one object a class. Assigned ID will distinguish array keys.
1
2 /**
3 * Singleton Repository
4 * @param string $class PHP Class Name
5 * @param string $id Optional Object ID
6 * @return reference Reference to existing Object
7 */
8 function &Singleton($class, $id='') {
9 static $singleton = array();
10 if (!array_key_exists($class.$id, $singleton))
11 $singleton[$class.$id] = &new $class();
12 $reference = &$singleton[$class.$id];
13 return $reference;
14 }
Use like this:
[edit] I'm sorry there was a mistake in the first exmaple for three days or so. Fixed.
1
2
3 $site_user=&Singleton('Student');
4 $site_user->Drink_Beer(5);
5
6
7 $current_user=&Singleton('Student');
8 echo $current_user->Show_Beers_Counter();
9
10
11
12 $one=&Singleton('Some_Class','one');
13 $two=&Singleton('Some_Class','two');
Works fine with PHP4, not tested on PHP5