【Foreword】
This article summarizes the PHP singleton pattern related
[Main body] Singleton mode
Simple understanding: a singleton is a class that can only be instantiated once and can only get one object
Shopping malls use singleton pattern
Idea: divided into steps
1. Create a common class; 2. Protect the constructor and encapsulate it (can not be called after protection); 3. Therefore, it needs to be called internally after encapsulation, so as to open an interface to the outside world;
4. Set as static, remove control, so that the call is not instantiated; 5. Add judgment; 6. Final prohibits inheritance
A single instance object, i.e. only one object can be instantiated
① Instances of common classes
<?php class Single{ public $rand; public function __construct(){ $this->rand = mt_rand(10,300);//mt_rand() random number } } var_dump(new Single());//115 var_dump(new Single());//148 ?>
Here I instantiate the class twice and get two objects with different values. This concludes that a class can instantiate multiple objects.
②Singleton pattern case
Instantiate into the class, plus conditional judgment
<?php class Single{ public $rand; static public $ob; protected function __construct(){ $this->rand = mt_rand(10,300);//random number } static public function out(){ if (Single::$ob === null) {//Determine whether to instantiate Single::$ob = new Single(); } return Single::$ob; } } var_dump(Single::out());//Output 222 var_dump(Single::out());//Output 222 ?>
same output twice
The above example has not been completed, because when the inherited subclass is instantiated again, it will still produce multiple different results
<?php class Single{ public $rand; static public $ob; //final is not allowed to be overridden by subclasses protected function __construct(){ $this->rand = mt_rand(10,300);//random number } static public function out(){ if (Single::$ob === null) {//Determine whether to instantiate Single::$ob = new Single(); } return Single::$ob; } } class Test extends Single{ public function __construct(){ echo rand(20,300);//This is overridden by subclasses } } new Test(); new Test(); ?>
For this we use final to prohibit overriding, because final classes cannot be inherited, and final methods cannot be overridden by subclasses
.