(給PHP開發者加星標,提升PHP技能)
轉自:Houzhyan
https://blog.csdn.net/h330531987/article/details/79100170
一、什麼是單例模式?
1、含義
作為對象的創建模式,單例模式確保某一個類只有一個實例,而且自行實例化並向整個系統全局地提供這個實例。它不會創建實例副本,而是會向單例類內部存儲的實例返回一個引用。
2、單例模式的三個要點:
(1). 需要一個保存類的唯一實例的靜態成員變量:
private static $_instance;(2). 構造函數和克隆函數必須聲明為私有的,防止外部程序new類從而失去單例模式的意義:
private function __construct() { $this->_db = pg_connect('xxxx'); } private function __clone() { }(3). 必須提供一個訪問這個實例的公共的靜態方法(通常為getInstance方法),從而返回唯一實例的一個引用
public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; }二、為什麼要使用單例模式?
1、PHP缺點:
PHP語言是一種解釋型的腳本語言,這種運行機制使得每個PHP頁面被解釋執行後,所有的相關資源都會被回收。也就是說,PHP在語言級別上沒有辦法讓某個對象常駐內存,這和asp.net、Java等編譯型是不同的,比如在Java中單例會一直存在於整個應用程式的生命周期裡,變量是跨頁面級的,真正可以做到這個實例在應用程式生命周期中的唯一性。然而在PHP中,所有的變量無論是全局變量還是類的靜態成員,都是頁面級的,每次頁面被執行時,都會重新建立新的對象,都會在頁面執行完畢後被清空,這樣似乎PHP單例模式就沒有什麼意義了,所以PHP單例模式我覺得只是針對單次頁面級請求時出現多個應用場景並需要共享同一對象資源時是非常有意義的。
2、單例模式在PHP中的應用場合:
(1)、應用程式與資料庫交互
一個應用中會存在大量的資料庫操作,比如過資料庫句柄來連接資料庫這一行為,使用單例模式可以避免大量的new操作,因為每一次new操作都會消耗內存資源和系統資源。
(2)、控制配置信息
如果系統中需要有一個類來全局控制某些配置信息, 那麼使用單例模式可以很方便的實現.
三、如何實現單例模式?
1、普通的資料庫訪問例子:
<?php . $db = new DB(...); $db->addUserInfo(...); . function getUserInfo() { $db = new DB(...); $db = query(....);} ?>2、應用單例模式對資料庫進行操作:
<?php class DB { private $_db; private static $_instance; private function __construct(...) { $this->_db = pg_connect(...); } private function __clone() {}; public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; } public function addUserInfo(...) { } public function getUserInfo(...) { } }
$db = DB::getInstance(); $db->addUserInfo(...); $db->getUserInfo(...);
?>3、深入理解
<?php class db { public $conn; public static $sql; public static $instance=null; private function __construct(){ require_once('db.config.php'); $this->conn = mysql_connect($db['host'],$db['user'],$db['password']); if(!mysql_select_db($db['database'],$this->conn)){ echo "失敗"; }; mysql_query('set names utf8',$this->conn); } public static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new db; } return self::$instance; } public function select($table,$condition=array(),$field = array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $fieldstr = ''; if(!empty($field)){ foreach($field as $k=>$v){ $fieldstr.= $v.','; } $fieldstr = rtrim($fieldstr,','); }else{ $fieldstr = '*'; } self::$sql = "select {$fieldstr} from {$table} {$where}"; $result=mysql_query(self::$sql,$this->conn); $resuleRow = array(); $i = 0; while($row=mysql_fetch_assoc($result)){ foreach($row as $k=>$v){ $resuleRow[$i][$k] = $v; } $i++; } return $resuleRow; } public function insert($table,$data){ $values = ''; $datas = ''; foreach($data as $k=>$v){ $values.=$k.','; $datas.="'$v'".','; } $values = rtrim($values,','); $datas = rtrim($datas,','); self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})"; if(mysql_query(self::$sql)){ return mysql_insert_id(); }else{ return false; }; } public function update($table,$data,$condition=array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $updatastr = ''; if(!empty($data)){ foreach($data as $k=>$v){ $updatastr.= $k."='".$v."',"; } $updatastr = 'set '.rtrim($updatastr,','); } self::$sql = "update {$table} {$updatastr} {$where}"; return mysql_query(self::$sql); } public function delete($table,$condition){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } self::$sql = "delete from {$table} {$where}"; return mysql_query(self::$sql); } public static function getLastSql(){ echo self::$sql; } } $db = db::getInstance(); $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password')); echo $db->delete('demo',array('id'=>'2')); db::getLastSql(); echo "<pre>"; ?>- EOF -
看完本文有收穫?請分享給更多人
關注「PHP開發者」加星標,提升PHP技能
點讚和在看就是最大的支持❤️