1. Define
A singleton pattern ensures that a class has only one instance, and instantiates it and provides this instance to the entire system globally. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.
2. Solve the problem/use scenario
In the case of database applications, a single example pattern can be used to avoid the resources consumed by a large number of new operations.
If you need a class in your system to control some of the configuration information globally, then using a single example pattern can be easily implemented.
3. Key points in implementing a single case model
A static member variable that holds a unique instance of the class is required.
Constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of the single case schema.
You need to provide a static method that accesses this instance (typically the GetInstance method), and returns a reference to the instance.
4. Implementing Code Examples
<?php Class singleton { private static $instance;
private $conn; private function __construct () {
$this->conn = mysql_connect (...); &NBSP;&NBSP;&NBSP;&NBSP} private function __clone () { } public static function getinstance () { if (!) ( Self:: $instance instanceof self) {
slef:: $instance = new self (); } return Self:: $instance; &NBSP;&NBSP;&NBSP;&NBSP} public function getdbconnect ()
{ return $this->conn; &NBSP;&NBSP;&NBSP;&NBSP} public function selectdata ($sql) { // $result mysql_query ($sql, $this->
conn); // while mysql_fetch_array ($result) ....
&NBSP;&NBSP} $db = singleton::getinstance (); $db->selectdata ("Select * from user");