This is a question I encountered in the php interview questions. The Singleton mode literally means that a class has only one instance. the benefits of doing so are great, such as database connection, we only need to instantiate the instance once and do not need to go to new every time. This greatly reduces the resource consumption singleton class and has at least three public 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:
The code is as follows:
/**
* 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 ();
?>