PHP Single-instance class

Source: Internet
Author: User

The singleton pattern literally means that there is only one instance of a class, so the benefits are 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, I have commented clearly in the following PHP example:

<?PHP/** * by www.phpddt.com*/    class Mysql{        //This property is used to save the instance        Private Static $conn; //The constructor is private, preventing the object from being created        Private function__construct () {$this->conn =mysql_connect(' localhost ', ' root ', '); }        //Create a method to instantiate an object         Public Static functiongetinstance () {if(! (Self::$conninstanceof Self)) { Self::$conn=NewSelf ; }            returnSelf::$conn; }        //prevent objects from being copied         Public function__clone () {Trigger_error(' Clone is not allowed! ')); }            }    //you can only get instances like this, not new and clone    $mysql=Mysql::getinstance ();?>

PHP Single-instance class

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.