A singleton class has at least the following three public elements:
Must have a constructor and must be marked private.
Has a static member variable that holds an instance of the class.
Has a public static method that accesses this instance
In terms of specific usage, I have clearly commented in the php example below:
Copy the code The code is as follows:
/**
* by www.phpddt.com
*/
class Mysql{
//This attribute is used to save the instance
private static $conn;
//The constructor is private, Prevent object creation
private function __construct(){
$this->conn = mysql_connect('localhost','root','');
}
//Create an instance Object method
public static function getInstance(){
if(!(self::$conn instanceof self)){
self::$conn = new self;
}
return self::$conn;
}
//Prevent the object from being copied
public function __clone(){
trigger_error('Clone is not allowed!');
}
}
//You can only get the instance in this way, not new and clone
$mysql = Mysql::getInstance();
?>
http://www.bkjia.com/PHPjc/326256.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326256.htmlTechArticleA singleton class has at least the following three public elements: It must have a constructor and must be marked as private. Have a static member variable that holds an instance of the class. Have a...