Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 0.97 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. PHP Don't allow object to instantiate more than once
  2. function __construct() {
  3.          self::$_instance =& $this;
  4.  
  5.          if (!empty(self::$_instance)) {
  6.             foreach (self::$_instance as $key => $class) {
  7.                      $this->$key = $class;
  8.             }
  9.          }
  10. }
  11.        
  12. class MyClass {
  13.     private static $instance = null;
  14.     private final function __construct() {
  15.         //
  16.     }
  17.     private final function __clone() { }
  18.     public final function __sleep() {
  19.         throw new Exception('Serializing of Singletons is not allowed');
  20.     }
  21.     public static function getInstance() {
  22.         if (self::$instance === null) self::$instance = new self();
  23.         return self::$instance;
  24.     }
  25. }
  26.        
  27. class Foo {
  28.     private static $instance;
  29.  
  30.     private function __construct() {
  31.     }
  32.  
  33.     public static function getInstance() {
  34.         if (!isset(static::$instance)) {
  35.             static::$instance = new static();
  36.         }
  37.  
  38.         return static::$instance;
  39.     }
  40. }