Php Singleton mode implementation (the object is created only once)

Source: Internet
Author: User
Tags php example

A singleton class has at least three common elements:

You must have a constructor and be marked as private.
Static member variables of an instance that stores classes.
Has a public static method to access this instance

For more information, see the following php example:

Copy codeThe Code is as follows: <? Php
/**
* By www.phpddt.com
*/
Class Mysql {
// This property is used to save the instance
Private static $ conn;
// The constructor is private to prevent object creation.
Private function _ construct (){
$ This-> conn = mysql_connect ('localhost', 'root ','');
}
// Create a method for instantiating an object
Public static function getInstance (){
If (! (Self: $ conn instanceof self )){
Self: $ conn = new self;
}
Return self: $ conn;
}
// Prevent objects from being copied
Public function _ clone (){
Trigger_error ('clone is not allowed! ');
}

}
// The instance can only be obtained in this way, not new or clone
$ Mysql = Mysql: getInstance ();
?>

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.