Advertisement
polosatique

PHP Singleton

Feb 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.56 KB | None | 0 0
  1. // General singleton class.
  2. class Singleton {
  3.   // Hold the class instance.
  4.   private static $instance = null;
  5.  
  6.   // The constructor is private
  7.   // to prevent initiation with outer code.
  8.   private function __construct()
  9.   {
  10.     // The expensive process (e.g.,db connection) goes here.
  11.   }
  12.  
  13.   // The object is created from within the class itself
  14.   // only if the class has no instance.
  15.   public static function getInstance()
  16.   {
  17.     if (self::$instance == null)
  18.     {
  19.       self::$instance = new Singleton();
  20.     }
  21.  
  22.     return self::$instance;
  23.   }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement