PHP Single-instance mode

Source: Internet
Author: User

Singleton mode: Refers to the pattern of an object, which refers to a class that can only create one object.

Since restricting a class can only create one object, it means shutting down other ways to create objects.

Therefore, to achieve a single case, you must meet the conditions:

1. Do not allow cloning (private cloning method)

2. Do not create object (private constructor method, cannot create object using the New keyword outside the class)

3. Creating an object in a class (static method)

4. Determine if the object exists, or create a new object if there is a return original

The advantage of using singleton mode is that you can save resources, such as DB class design, such as Window System common resource Manager.

<?PHPclasssingle{//defining an attribute to save an object    Private Static $single; //Private Construction Methods    Private function__construct ($name){        $this->name =$name;    }        //privatization Cloning Method    Private function__clone () {    }        //static method: Let the class enter into the inside of the class to instantiate the resulting object      Public Static functionGetInstance ($name){         //determines whether an object exists, or creates a new object if there is a return original         if(!self::$single) { self::$single=NewSingle ($name); }         returnSelf::$single; }}$single= Single::getinstance (' Libai ');Var_dump($single);$single= Single::getinstance (' Dufu ');Var_dump($single);

PHP Single-instance 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.