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