In the daily development process, often encounter some classes do not need to re-instantiate, such as database connection, in this case, the singleton mode is the best solution. Just the last interview has been asked about this model, today to make a summary.
Let's take a look at one of the simplest implementations of the singleton pattern:
<?phpclass singleton{ static $instance; static function getinstance () { if (Is_null (self:: $instance)) {self :: $instance = new self (); } Return self:: $instance; }} $test 1 = singleton::getinstance (), $test 2 = singleton::getinstance (), if ($test 1 = = = $test 2) { echo "is the same object";} else{ echo "Not the same object";}
The results of the operation are as follows:
But this is strictly not a true singleton pattern, because the user can simply instantiate new objects by using the newly keyword.
$test 1 = new Singleton (), $test 2 = new Singleton ();
The results of the operation are as follows:
So we're going to make a little improvement on our code to set the access level of the construction method to protected:
<?phpclass singleton{ static $instance; protected function __construct () { } static function getinstance () { if (Is_null (self:: $instance)) { Self:: $instance = new self (); } Return self:: $instance; }} $test 1 = new Singleton (), $test 2 = new Singleton (), if ($test 1 = = = $test 2) { echo "is the same object";} else{ echo "Not the same object";}
When the user attempts to instantiate a new object with the newly keyword, the error is reported as follows:
Of course, a cunning user can still clone a new object by using the Clone keyword:
$test 1 = singleton::getinstance (), $test 2 = Clone $test 1;if ($test 1 = = = $test 2) { echo "is the same object";} else{ echo "Not the same object";}
Operation Result:
So we're going to declare the __clone method as protected:
<?phpclass singleton{ static $instance; protected function __construct () { } static function getinstance () { if (Is_null (self:: $instance)) { Self:: $instance = new self (); } Return self:: $instance; } protected function __clone () { }} $test 1 = singleton::getinstance (), $test 2 = Clone $test 1;if ($test 1 = = = $test 2) { echo "is the same object";} else{ echo "Not the same object";}
When a user attempts to clone a new object with the Clone keyword, the error is reported as follows:
Therefore, in order to achieve a strict implementation of a single-case model, we should pay attention to the following points:
1, declare the constructor function as protected;
2. Create a static method of getinstance to get the static variable that holds the class;
3. Declare the __clone method as protected
Of course, in the actual development, in most cases as long as the implementation of a simple singleton mode (the first example of the wording).
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Getting Started with PHP design mode-Singleton mode