Monday 17 May 2010

How to create Singleton Class in PHP

<?php
class singleton
{
  
     /** Store the instance of the class */
     private static $instance;
    
     private function __construct()
     {
     }
    
     public static function getInstance()
     {
         //__CLASS__ is always resolved to this class, even if subclassed
         if (!self::$instance instanceof self)
         {
             self::$instance = new self();
         }
        
         return self::$instance;
     }
    
     public function __clone()
     {
        throw new Exception("Cloning of this object is not supported.");
     }
    
     public function someMethod()
     {
         echo "Doing something!";
     }

}
?>

No comments:

Post a Comment