Home > Article > Backend Development > Getting Started with PHP Design Patterns - Singleton Pattern_PHP Tutorial
Let’s first look at the implementation of the simplest singleton pattern:
<!--?php class Singleton{ static $instance; static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $test1 = Singleton::getInstance(); $test2 = Singleton::getInstance(); if($test1 === $test2){ echo 是同一个对象; }else{ echo 不是同一个对象; } </pre--> 运行结果如下:
But just writing it like this is not a true singleton pattern in a strict sense, because users can instantiate new objects through the new keyword.
$test1 = new Singleton(); $test2 = new Singleton();The running results are as follows:
So we have to make a little improvement to our code and set the access level of the constructor to protected:
<!--?php class Singleton{ static $instance; protected function __construct(){ } static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $test1 = new Singleton(); $test2 = new Singleton(); if($test1 === $test2){ echo 是同一个对象; }else{ echo 不是同一个对象; } </pre-->这时当用户试图以new关键词实例化一个新的对象时,会报如下截图所示的错误:
Of course, cunning users can still clone a new object through the clone keyword:
$test1 = Singleton::getInstance(); $test2 = clone $test1; if($test1 === $test2){ echo 是同一个对象; }else{ echo 不是同一个对象; }
So we also need to declare the __clone method as protected:
<!--?php class Singleton{ static $instance; protected function __construct(){ } static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } protected function __clone(){ } } $test1 = Singleton::getInstance(); $test2 = clone $test1; if($test1 === $test2){ echo 是同一个对象; }else{ echo 不是同一个对象; } </pre-->时当用户试图以clone关键词克隆一个新的对象时,会报如下截图所示的错误:
So to implement a singleton pattern in a strict sense, you should pay attention to the following points:
1. Declare the constructor as protected;
2. Create a static method of getInstance to obtain the static variables that save the class;
3. Declare the __clone method as protected
Of course, in actual development, in most cases it is enough to implement a simple singleton pattern (the way the first example is written).