Single-Case mode
Singleton mode is useful when you need to ensure that an object can have only one instance. It delegates control of the created object to a single point, and at any time the application will only have one instance to exist.
The singleton pattern must contain: private constructor, static variable, public static method, private Clone method.
Here's a chestnut.
<?PHP/** MySQL single case*/class MySQL{ Private $host= ' Yourhost ';//Database Host Private $user= ' Youruser ';//Database user name Private $pwd= ' yourpwd ';//database user name password Private $database= ' database ';//Database name Private $charset= ' UTF8 ';//database encoding, gbk,utf8,gb2312 Private $link;//database connection identification; Private $rows;//multi-row array obtained by query Static $_instance;//Storage Objects /** * Private Constructors*/ Private function__construct ($pconnect=false) { if(!$pconnect) { $this->link = @mysql_connect($this->host,$this->user,$this->PWD) or$this-err (); } Else { $this->link = @Mysql_pconnect($this->host,$this->user,$this->PWD) or$this-err (); } mysql_select_db($this->database) or$this-err (); $this->query ("SET NAMES ' {$this->charset} ' ",$this-link); return $this-link; } /** * Prevent cloning **/ Private function__clone () {} Public Static functionGetInstance ($pconnect=false){ if(FALSE= = (self::$_instanceinstanceof Self)) { Self::$_instance=NewSelf$pconnect); } returnSelf::$_instance; } /** * Enquiry*/ Public functionQuery$sql,$link= ' ') { $this->result =mysql_query($sql,$this->link) or$this->err ($sql); return $this-result; } /** * Single record*/ Public functionGetRow ($sql,$type=Mysql_assoc) { $result=$this->query ($sql); return@Mysql_fetch_array($result,$type); } /** * Multi-line record*/ Public functionGetRows ($sql,$type=Mysql_assoc) { $result=$this->query ($sql); while($row= @Mysql_fetch_array($result,$type)) { $this->rows[] =$row; } return $this-rows; } /** * error message output*/ protected functionErr$sql=NULL) { }}//Use Cases$db=MySQL::getinstance ();$db 2=MySQL::getinstance ();$data=$db->getrows (' select * FROM blog ');//Print_r ($data);//Determine if two objects are equalif($db===$db 2){ Echo' True ';}?>
PHP Single-instance mode