Return to Snippet

Revision: 2398
at February 9, 2007 14:38 by drwitt


Updated Code
/**
 * 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;
}


# 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');

Revision: 2397
at February 8, 2007 04:50 by drwitt


Initial Code
/**
 * 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;
}


# 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');

Initial URL

                                

Initial Description

                                

Initial Title
Flexible Singleton

Initial Tags
php, object, ruby

Initial Language
PHP