php 單例模式
阿新 • • 發佈:2018-05-10
span php sql gb2312 pre 連接 ceo 單例 數據
單例模式
當需要保證某個對象只能有一個實例的時候,單例模式非常有用。它把創建對象的控制權委托到一個單一的點上,任何時候應用程序都只會僅有一個實例存在。
單例模式中必須包含:private 的構造函數、靜態變量、公共靜態方法、private clone方法。
下面舉個栗子
<?php /* * mysql 單例 */ class mysql{ private $host =‘yourhost‘; //數據庫主機 private $user = ‘youruser‘; //數據庫用戶名 private $pwd = ‘yourpwd‘; //數據庫用戶名密碼 private$database = ‘database‘; //數據庫名 private $charset = ‘utf8‘; //數據庫編碼,GBK,UTF8,gb2312 private $link; //數據庫連接標識; private $rows; //查詢獲取的多行數組 static $_instance; //存儲對象 /** * 私有構造函數 */ 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; } /** * 防止被克隆 * */ private function __clone(){} public static function getInstance($pconnect = false){ if(FALSE == (self::$_instance instanceof self)){ self::$_instance = new self($pconnect); } return self::$_instance; } /** * 查詢 */ public function query($sql, $link = ‘‘) { $this->result = mysql_query($sql, $this->link) or $this->err($sql); return $this->result; } /** * 單行記錄 */ public function getRow($sql, $type = MYSQL_ASSOC) { $result = $this->query($sql); return @ mysql_fetch_array($result, $type); } /** * 多行記錄 */ public function getRows($sql, $type = MYSQL_ASSOC) { $result = $this->query($sql); while ($row = @ mysql_fetch_array($result, $type)) { $this->rows[] = $row; } return $this->rows; } /** * 錯誤信息輸出 */ protected function err($sql = null) { } } //用例 $db = mysql::getInstance(); $db2 = mysql::getInstance(); $data = $db->getRows(‘select * from blog‘); //print_r($data); //判斷兩個對象是否相等 if($db === $db2){ echo ‘true‘; } ?>
php 單例模式