Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active September 27, 2017 07:12
Show Gist options
  • Select an option

  • Save evgv/3aacc34acd849b8b7ba039b117e42261 to your computer and use it in GitHub Desktop.

Select an option

Save evgv/3aacc34acd849b8b7ba039b117e42261 to your computer and use it in GitHub Desktop.
PHP. Pattern: Singleton

Simple example of Singleton design pattern

A singleton class is a class that can have only one object (an instance of the class) at a time.

Lasy load Singleton

The instance is created when the static method is first invoked.

  
/**
* Lazy load Simple example of Singleton design pattern 
*/
final class Singleton 
{
   /**
    * Variable for store instance
    *
    * @var Singleton $instance
    */ 
    private static $instance = null;
        
   /** 
    * The constructor __construct() is declared as protected
    * to prevent creating a new instance outside of the class 
    * via the new operator.Constructor is private 
    */
    private function __construct() 
    {
        // some code, connect to db etc.
    }
   
   /** 
    * The magic method __clone() is declared as private
    * to prevent cloning of an instance of the class via the clone operator.
    */
    private function __clone() 
    {
        //    
    }
    
   /**
    * The magic method __wakeup() is declared as private 
    * to prevent unserializing of an instance of the class 
    * via the global function unserialize()
    */
    private function __wakeup() 
    {
        //    
    }
    
   /**
    * Create instance of object 
    * if it is not exist or return existed
    *
    * @return Singleton
    */
    static public function getInstance() 
    {
        if (is_null(self::$instance)) {
            self::$instance = new Singleton();
        }
        
        return self::$instance;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment