Posted By

DaveChild on 09/17/08


Tagged

Singleton


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

elgermano
Scooter
sarfraznawaz2005
xmartyxcorex


PHP Singleton Class


 / Published in: PHP
 

Not extensively tested but should work just fine!

  1. <?php
  2.  
  3. /**
  4.   * Singleton object. Usage:
  5.   * $objInstance = Singleton::getInstance('ClassName');
  6.   */
  7. class Singleton {
  8.  
  9. private static $arrInstances = array();
  10.  
  11. private function __construct() {
  12. }
  13.  
  14. public function getInstance($strClassName) {
  15. $strClassNameKey = strtolower($strClassName);
  16. if (!array_key_exists($strClassNameKey, self::$arrInstances)) {
  17. self::$arrInstances[$strClassNameKey] = new $strClassName;
  18. }
  19. return self::$arrInstances[$strClassNameKey];
  20. }
  21. }
  22.  
  23. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: MichaelR on December 22, 2009

It should be:

public STATIC function getInstance ($strClassName) { ... }

(Capitalization just to emphasize my fix).

Posted By: MichaelR on December 22, 2009

Note; you can also define the class as abstract, and then not need to have a private __construct().

You need to login to post a comment.