A simple example of PHP's singleton pattern

Source: Internet
Author: User

Singleton: A class can always produce only one object.

First, you have to let this class fail to produce new objects. There are two ways to generate new objects in PHP: New and clone, If you privatize the construction method and the Clone method, you can prevent the creation of the object from being instantiated outside of the class and not allowing cloning. This will solve the problem of not allowing the class to produce new objects. Take the person class as an example.

1 class  Person 2 {3     Private function __construct () {}  //constructor method 4     Private function __clone () {}  //Cloning method 5 }

Since there is no way to produce new objects at this time, there is no way to instantiate, then this class needs a public static method to get this "forever object", then how to ensure that every time the method is called to get the object is the "Forever object" it? You may need to define a static private property, $instance, to determine whether $instance is an object when invoking the Fetch method, or not to create a new object, and then return directly to $instance. The implementation code is as follows:

1 class Person2 {3     Private Static $instance;4     Private function__construct () {}5     Private function__clone () {}6 7      Public Static functiongetinstance () {8         if(!Is_object(Self::$instance)) {9Self::$instance=NewSelf ;Ten         } One         returnSelf::$instance; A     } -}

Test code:

1 $i 1 = Person::getinstance (); 2 Echo "I1:"; 3 Var_dump ($i 1); 4 Echo "; 5 Echo "I2:"; 6 $i 2 = Person::getinstance (); 7 Var_dump ($i 2);

Output Result:

The result is the same number of two objects as the same object. This is the singleton pattern.

A simple example of PHP's singleton pattern

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.