實現單例模式:單例模式是一種經常使用的軟件設計模式。在它的核心結構中只包含一個被稱爲單例的特殊類。經過單例模式能夠保證系統中一個類只有一個實例。mysql
單例模式的邏輯:類裏面聲明一個靜態的方法和變量,靜態變量用來存儲惟一的實例,靜態方法做爲類向外的惟一的接口,並在裏面作判斷,當靜態變量有實例時候直接返回,沒有則new一個實例賦值在靜態變量裏面。構造函數裏面放連接數據庫的操做,由於靜態方法中實現了控制了只實例化一次,因此達到只連接數據庫一次。在類外部訪問靜態方法;sql
簡單類以下:數據庫
1 class Con_db{ 2 private static $dbObj = null; 3 private $con; 4 private $result; 5 private $row; 6 private $newsItem; 7 /** 8 * 構造函數 9 * @param [type] $host [數據庫地址] 10 * @param [type] $username [數據庫名稱] 11 * @param [type] $psw [數據庫密碼] 12 * @param [type] $database [數據庫] 13 */ 14 private function __construct($host,$username,$psw,$database){ 15 $this->con = mysql_connect($host,$username,$psw); 16 if(!$this->con){ 17 die("連接失敗"); 18 } 19 mysql_set_charset("utf-8"); 20 mysql_select_db($database); 21 } 22 /** 23 * 獲取一次性對象 24 * @return 實例對象 25 */ 26 public static function getInstance($host,$username,$psw,$database){ 27 if(is_null(self::$dbObj)){ 28 self::$dbObj = new self($host,$username,$psw,$database); 29 } 30 return self::$dbObj; 31 } 32 33 /** 34 * 數據庫查詢語句 35 */ 36 private function query($sql){ 37 if($sql){ 38 $this->result = mysql_query($sql); 39 if($this->result && mysql_num_rows($this->result)){ 40 return $this->result; 41 }else{ 42 return false; 43 } 44 }else{ 45 die("必須填寫查詢語句!"); 46 } 47 } 48 /** 49 * 查詢多條語句 50 * @param $sql 查詢語句 51 * return string; 52 */ 53 private function getAll($sql){ 54 $this->result = mysql_query($sql); 55 if($this->result && mysql_num_rows($this->result)){ 56 $this->newsItem = array(); 57 while($this->row = mysql_fetch_assoc($this->result)){ 58 $this->newsItem[] = $this->row; 59 } 60 } 61 return $this->newsItem; 62 } 63 /** 64 * 查詢一條語句 65 * @param $sql 查詢語句 66 * return string; 67 */ 68 private function getone($sql){ 69 $this->result = mysql_query($sql); 70 if($this->result && mysql_num_rows($this->result)){ 71 return $this->row = mysql_fetch_assoc($this->result); 72 } 73 } 74 } 75 $db = Con_db::getInstance("localhost","root","root","szwengdo_com"); 76 $sql = "select * from wd_cases"; 77 $row = $db->getone($sql); 78 var_dump($row);
第一次研究,但願改正!!設計模式