Simple example of php Singleton mode

Source: Internet
Author: User
Simple example of php Singleton mode Singleton: A class can always produce only one object.

First, make this class unable to produce new objects. There are two ways to generate new objects in php: new and clone. if you privatize the constructor and clone methods, you can prevent new objects from being generated when the class is instantiated externally and not cloned. In this way, the class cannot produce new objects. Take the Person class as an example.

1 class Person2 {3 private function _ construct () {}// constructor 4 private function _ clone () {}// cloning method 5}

Since there is no way to generate new objects or instantiate them at this time, this class requires a public static method to obtain this "forever object ", so how can we ensure that every time we call this method to obtain an object is the "forever object? You can define a static private attribute $ instance. when calling the GET method, you can determine whether $ instance is an object. if not, you can create a new object. If yes, $ instance is directly returned. The implementation code is as follows:

 1 class Person 2 { 3     private static $instance; 4     private function __construct(){} 5     private function __clone(){} 6  7     public static function getInstance(){ 8         if (!is_object(self::$instance)) { 9             self::$instance = new self;10         }11         return self::$instance;12     }13 }

Test code:

1 $i1 = Person::getInstance();2 echo "i1:";3 var_dump($i1);4 echo "
 ";5 echo "i2:";6 $i2 = Person::getInstance();7 var_dump($i2);

Output result:

The result is that the numbers of the two objects are the same, that is, the same object. This is the singleton mode.

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.