Php design mode-singleton mode, php design mode-Mode
For a single instance, a class provides an instance through an interface and cannot create a new instance through new or clone.
The key to single-instance implementation is implemented through a static method getInstance. This method only returns the unique instance of this class. When this method is called for the first time, it creates an instance, put it in a private static variable. Next time, you only need to return the previously created instance to achieve the effect of Singleton.
1 class Log {2 static private $ instance = NULL; 3 4 private function _ construct () {5} 6 7 private function _ clone () {8} 9 10 function log ($ str) {11 echo $ str. PHP_EOL; 12} 13 14 static function getInstance () {15 if (self ::$ instance = NULL) {16 self ::$ instance = new Log (); 17} 18 return self: $ instance; 19} 20} 21 22 Log: getInstance ()-> log ("warning info"); 23 Log: getInstance () -> log ("error info"); 24 // the following error 25 new Log ();
Here, the constructor and the _ clone method are declared as private to prevent users from using new or clone to generate new instances.