PHP Singleton mode Implementation object is only created once MySQL single-instance operation class

Source: Internet
Author: User
Tags php example

This is a question I encountered in the PHP interview, the singleton pattern literally is a certain class only one instance, the benefits are still very large, such as database connection, we only need to instantiate once, do not need to go to new each time, this greatly reduces the cost of resources.

The Singleton class has at least the following three common elements:

Must have a constructor and must be marked private.
has a static member variable that holds an instance of the class.
Have a public static method that accesses this instance

For specific use, the following PHP example notes clearly:

1<?PHP2     /**3 * by Www.phpddt.com4      */5     class Mysql{6         //This property is used to save the instance7         Private Static $conn;8         //The constructor is private, preventing the object from being created9         Private function__construct () {Ten             $this->conn =mysql_connect(' localhost ', ' root ', '); One         } A         //Create a method to instantiate an object -          Public Static functiongetinstance () { -             if(! (Self::$conninstanceof Self)) { theSelf::$conn=NewSelf ; -             } -             returnSelf::$conn; -         } +         //prevent objects from being copied -          Public function__clone () { +             Trigger_error(' Clone is not allowed! ')); A         } at          -     } -     //you can only get instances like this, not new and clone -     $mysql=Mysql::getinstance (); -?>

PHP Singleton mode Implementation object is only created once MySQL single-instance operation class

Related Article

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.