Today let’s talk about the singleton pattern.
Because I used to do java development, when using the singleton mode, I first thought of using the hungry Chinese style, and then I found that in PHP, there is such a feature: because PHP does not support giving in the class definition Member variables of a class are assigned values of non-basic types. Such as expressions, new operations, etc. So the Hungry Chinese style will not work. Instead, I wanted to ensure the atomicity of this singleton mode, and found that there are no thread safety issues in PHP like in JAVA. Hey, do you think PHP is good? OK, then let’s try PHP’s lazy singleton mode.
Let’s not talk about it for now, let me start with my first version of the singleton mode code:
// 定义私有静态变量.此种方式为:懒汉式单例(PHP中只有这种方式) private static $instance = null; // 私有化构成方法 private function __construct(){ } // 提供获取实例的公共方法 public static function getInstance(){ if(!(self::$instance instanceof self)){ self::$instance = new self(); } return self::$instance; } // 私有__clone方法,禁止复制对象 private function __clone(){ }
My class A is in singleton mode, and then my class B inherits from class A, and then I call the following method:
$a = A::getInstance(); $b = B::getInstance(); var_dump($a === $b);
$b = B::getInstance();
The problem lies with self. The reference of self is determined when the class is defined. That is to say, if A inherits B, its self reference still points to A. To solve this problem, the late static binding feature was introduced in PHP 5.3. Simply put, static methods or variables are accessed through the static keyword. Unlike self, static references are determined at runtime. So we simply rewrite our code so that the singleton mode can be reused.
class C { protected static $_instance = null; protected function __construct(){ } protected function __clone(){ } public function getInstance(){ if (static::$_instance === null) { static::$_instance = new static; } return static::$_instance; } } class D extends C{ protected static $_instance = null; } $c = C::getInstance(); $d = D::getInstance(); var_dump($c === $d);
Then it can be achieved. As long as you inherit this singleton mode, then its subclasses will also be singleton mode. This can achieve perfect reuse without having to write so much repeated code every time you need the singleton mode. Note that the above method can only be used in PHP 5.3. For previous versions of PHP, it is better to write a getInstance() method for each singleton class.
The above has introduced the third part of API development: PHP's design pattern - the perfect singleton pattern, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.