Flexible Singleton


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Singleton Repository
  3.  * @param string $class PHP Class Name
  4.  * @param string $id Optional Object ID
  5.  * @return reference Reference to existing Object
  6.  */
  7. function &Singleton($class, $id='') {
  8. static $singleton = array();
  9. if (!array_key_exists($class.$id, $singleton))
  10. $singleton[$class.$id] = &new $class();
  11. $reference = &$singleton[$class.$id];
  12. return $reference;
  13. }
  14.  
  15.  
  16. # first call: create object
  17. $site_user=&Singleton('Student');
  18. $site_user->Drink_Beer(5);
  19.  
  20. # second call: get a reference
  21. $current_user=&Singleton('Student');
  22. echo $current_user->Show_Beers_Counter();
  23. #will be 5
  24.  
  25. #Two different objects
  26. $one=&Singleton('Some_Class','one');
  27. $two=&Singleton('Some_Class','two');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.