Simple example of php Singleton mode
Singleton: A class can always produce only one object.
First, make this class unable to produce new objects. There are two ways to generate new objects in php: new and clone. if you privatize the constructor and clone methods, you can prevent new objects from being generated when the class is instantiated externally and not cloned. In this way, the class cannot produce new objects. Take the Person class as an example.
1 class Person2 {3 private function _ construct () {}// constructor 4 private function _ clone () {}// cloning method 5}
Since there is no way to generate new objects or instantiate them at this time, this class requires a public static method to obtain this "forever object ", so how can we ensure that every time we call this method to obtain an object is the "forever object? You can define a static private attribute $ instance. when calling the GET method, you can determine whether $ instance is an object. if not, you can create a new object. If yes, $ instance is directly returned. The implementation code is as follows:
1 class Person 2 { 3 private static $instance; 4 private function __construct(){} 5 private function __clone(){} 6 7 public static function getInstance(){ 8 if (!is_object(self::$instance)) { 9 self::$instance = new self;10 }11 return self::$instance;12 }13 }
Test code:
1 $i1 = Person::getInstance();2 echo "i1:";3 var_dump($i1);4 echo "
";5 echo "i2:";6 $i2 = Person::getInstance();7 var_dump($i2);
Output result:
The result is that the numbers of the two objects are the same, that is, the same object. This is the singleton mode.