Platinum Partner

Flexible Singleton

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.


/**
 * Singleton Repository
 * @param string $class PHP Class Name
 * @param string $id Optional Object ID
 * @return reference Reference to existing Object
 */
function &Singleton($class, $id='') {
  static $singleton = array();
  if (!array_key_exists($class.$id, $singleton))
    $singleton[$class.$id] = &new $class();
  $reference = &$singleton[$class.$id];
  return $reference;
}


Use like this:
[edit] I'm sorry there was a mistake in the first exmaple for three days or so. Fixed.

# first call: create object
$site_user=&Singleton('Student');
$site_user->Drink_Beer(5);

# second call: get a reference
$current_user=&Singleton('Student');
echo $current_user->Show_Beers_Counter();
#will be 5

#Two different objects
$one=&Singleton('Some_Class','one');
$two=&Singleton('Some_Class','two');


Works fine with PHP4, not tested on PHP5
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}