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:
Copy the Code code as follows:
/**
* 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 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! ');
}
}
You can only get instances like this, not new and clone
$mysql = Mysql::getinstance ();
?>
http://www.bkjia.com/PHPjc/326256.html www.bkjia.com true http://www.bkjia.com/PHPjc/326256.html techarticle a singleton class has at least the following three common elements: a constructor must be owned and must be marked private. has a static member variable that holds an instance of the class. To have a ...