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 ();
?>