PHP Single-instance mode detailed

Source: Internet
Author: User
In fact, a singleton pattern, plainly speaking, is that a class can only be instantiated once. But how do we make a fuss at this instantiation? In fact, there is a breakthrough is __construct () this magic method. This method means that the method is automatically executed if the class is instantiated. And if I turn this method into a protection or a private one, what would it be?


<?phpclass test{protected function __construct () {}} $test = new test (); >

This happens when you do the following.

&amp;amp;lt;img data-rawheight=&quot;125&quot; data-rawwidth=&quot;994&quot; src=&quot;http://img.php.cn/upload/article/000/054/025/a79c550120d3e119df603c5755b0f293-0.jpg&quot; Class=&quot;origin_image zh-lightbox-thumb&quot; width=&quot;994&quot; Src=&quot;https://pic4.zhimg.com/3a977167d4bb4083db5218628d34e0d3_r.jpg&quot;&amp;amp;gt; like that, It cannot be instantiated. This ensures that no one is allowed to instantiate it casually.
But in that case, how should we instantiate it? That's it:


<?phpclass test{protected function __construct () {}public static function getinstance () {$_test = new test (); return $_ Test;}} $test = Test::getinstance (); Var_dump ($test);? >

In that case. example, you can show up. Let's take a look at:
&amp;amp;lt;img data-rawheight=&quot;50&quot; data-rawwidth=&quot;152&quot; src=&quot;http://img.php.cn/upload/article/000/054/025/a79c550120d3e119df603c5755b0f293-1.jpg&quot; class=&quot;content_image&quot; Width=&quot;152&quot;&amp;amp;gt; But speaking so much, I still didn't say the point. Here's the point, as long as we use one more keyword (static). A clang of a clang:


<?phpclass test{protected function __construct () {}public static function GetInstance () {Static $_test;if (empty ($_test)) {$_test = new test ();} return $_test;}} $test 1 = test::getinstance (), $test 2 = Test::getinstance (), $test 3 = Test::getinstance (); Var_dump ($test 1, $test 2, $test 3 ) echo $test 1 = = $test 2? ' True ': ' false ', echo ' <br> ', echo $test 2 = = $test 3? ' True ': ' false ', echo ' <br> ', echo $test 1 = = $test 3? ' True ': ' false ';? 

Look at the results:
&amp;amp;lt;img data-rawheight=&quot;160&quot; data-rawwidth=&quot;133&quot; src=&quot;http://img.php.cn/upload/article/000/054/025/a79c550120d3e119df603c5755b0f293-2.jpg&quot; class=&quot;content_image&quot; Width=&quot;133&quot;&amp;amp;gt; this way, you can achieve PHP single-case results.
In the case of a singleton, the longest use is to use only this class, instead of having more than one class.
Make an analogy. For example, there is now a config class, this class is mainly to store the configuration information of this project. If this class can be instantiated multiple times, then if the configuration has been modified in the code run, then how do you know in which configuration class has been modified. At this point, the singleton mode is used to avoid the situation, and all changes to the configuration file are based on the instance of this class. Instead of being instantiated by multiple classes, the operation is not updated in real-time with the changes to the operation. Also, instances of multiple class libraries can be very expensive to use, and only instantiate once. is not a lot of benefits.

Other Insights:

To privatize the clones, too.

Class Test{private static $instance;p rivate function __construct () {}private function __clone () {}public static function GetInstance () {if (! Self:: $instance instanceof Self) {self:: $instance = new self ();} Return self:: $instance;}}

More Intuitive methods:

Click to open link


/* Singleton design mode (single State) definition: A class can only allow one object to exist. 1. Do not allow the class to be instantiated 2. Leave the back door: Set static Method 3. To object: Instantiate the Class 4 in a static method. The first night: to determine whether it was the object that generated the class for the second 5. Set static: Static method to use static attribute *//*//1. Do not allow the class to be    can be instantiated-----------------class test{//Set a package construction method private Function __construct () {//placeholder, I just won't let you new me ~ ~ ~ }}*//*//2. Leaving the back door: Setting a static method--------------------class test{//setting an encapsulated construction method private Function __construct () {//placeholder    , I just won't let you new me ~ ~}//Backdoor public static function GetObject () {echo "Ah, I am the back door, into the!<br>"; }}*//*//3. To an object: Instantiate the class in a static method------------------class test{//Set a package construction method private Function __construct () {/        /placeholder, I just won't let you new me ~ ~}//Backdoor public static function GetObject () {echo "Ah, I am the back door, into the!<br>"; return new self ();//Instantiate an object to give you}}*//*//4. The first time to judge is whether the object that generated the class is------------------class test{Private $obj = null;//Property value As an object, the default is NULL//set an encapsulated construction method private Function __construct () {//placeholder, I just won't let you new me ~ ~}//Backdoor public static function GetObject () {echo "Ah, I am the back door, enter the!<br>"; if ($this->obj = = = null) {$this->obj = new self ();//Instantiate an Object}//The Returned property is actually this object retur    N $this->obj;    }}*///5. Static: Static method to use static property------------------class test{private static $obj = null;//Property value is an object, default is NULL//set an encapsulated construction method        Private Function __construct () {//placeholder, I just won't let you new me ~ ~}//Backdoor public static function GetObject () {        echo "Ah, I am the back door, enter the!<br>"; if (self:: $obj = = = null) {self:: $obj = new self ();//Instantiate an Object}//The Returned property is actually the object return self    :: $obj; }}/*test::getobject ();//Use static methods to access methods in the class exit;*/$t 1 = test::getobject (), $t 2 = Test::getobject (), $t 3 = Test::getobject () ; $t 4 = Test::getobject (); $t 5 = Test::getobject (); $t 6 = Test::getobject (); $t 7 = Test::getobject (); $t 8 = Test::getobject () ;//Determine if the two objects are the same object if ($t 1 = = =-$t 6) {echo "Oh, yes! Is the same instance <br> ";} else {echo "Oh, no! Not the same instance <br> ";}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.