PHP singleton mode implementation (object is only created once)_PHP tutorial

WBOY
Release: 2016-07-21 15:14:26
Original
926 people have browsed it

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

www.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...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template