Posted By

koncept on 01/16/07


Tagged

php php5 Singleton


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

riccardo
dittonamed
shikee
nfreear
Priestd09


PHP5 Singleton Design Pattern


 / Published in: PHP
 

  1. <?php
  2. /**
  3.  * Singleton design pattern implementation for PHP5
  4.  */
  5. class Singleton
  6. {
  7. private static $instances = array();
  8.  
  9. private function __construct(){}
  10.  
  11. public static function getInstance( $class = null )
  12. {
  13. if( is_null( $class ) )
  14. {
  15. trigger_error( "Missing class information", E_USER_ERROR );
  16. }
  17. if( !array_key_exists( $class, self::$instances ) )
  18. {
  19. self::$instances[ $class ] = new $class;
  20. }
  21. return self::$instances[ $class ];
  22. }
  23. public final function __clone()
  24. {
  25. trigger_error( "Cannot clone instance of Singleton pattern", E_USER_ERROR );
  26. }
  27. }
  28.  
  29. // Usage
  30. $instance = Singleton::getInstance( 'SomeClass' );
  31. ?>

Report this snippet  

You need to login to post a comment.