PHP _ Singleton mode, instance code, and php instance code
If an object is instantiated in PHP, a new memory space will be opened up. When some businesses need to instantiate multiple objects, a large amount of memory will be occupied. This problem can be solved in singleton mode.
The instantiated object can be new directly, or through the constructor _ construct, destructor _ destruct, and clone _ clone in the class, we can privatize these three functions to prevent external entities from instantiating objects like this; then we can set a public static method called by class name. This is "three private and one public ".
The Code is as follows:
1 <? Php 2 3 // create a class first, next, call 4 class A {5 6} 7 8 // create Singleton class 9 One {10 // set A private static Property to save the object 11 private static $ obj; 12 13 // privatize the constructor 14 private function _ construct () {15} 16 17 // create a public static method, the static method is to call 18 static function getObj ($ className) directly through the class name) {19/** 20 * instanceof check whether an object belongs to this class 21 * if the instantiated object belongs to this class 22 */23 if (self ::$ obj instanceof $ className) {24 // return this object 25 return self: $ obj; 26} else {27 // if not, instantiate this object and return 28 self :: $ obj = new $ className; 29 return self: $ obj; 30} 31} 32 33 // private clone 34 private function _ clone () {35} 36} 37 38 // test 39 // no matter how many Class A is instantiated, only One object 40 $ one1 = One: getObj ('A') will be obtained '); 41 $ one2 = One: getObj ('A'); 42 $ one3 = One: getObj ('A'); 43 var_dump ($ one1 ); 44 var_dump ($ one2); 45 var_dump ($ one3 );