類的單例模式只須要執行一次數據庫鏈接,能夠防止數據庫的屢次鏈接給服務器形成負擔php
PHP示例代碼mysql
<?php require_once 'config.php'; class DB { protected $host; protected $user; protected $password; protected $dbname; protected $db; protected static $c; //構造函數 初始化 私有 禁止外部調用 private function __construct($host = DB_DBNAME, $user = DB_USER, $password = DB_PASSWORD, $dbname = DB_NAME) { $this->host = $host; $this->user = $user; $this->password = $password; $this->dbname = $dbname; // 判斷數據庫是否鏈接 if ($this->db) { $this->db = conn(); } } // 鏈接數據庫 function conn() { $conn = new mysqli($this->host, $this->user, $this->password); if ($conn->connect_error) { echo '數據庫鏈接失敗,錯誤信息:' . $conn->connect_error; } // 選擇數據庫 $conn->select_db($this->dbname); // 設置字符集 $conn->set_charset('utf8'); $this->db = $conn; } // 禁止克隆 private function __clone() { } // 單例模式 public static function init(){ // 判斷靜態變量$c是不是本類的實例化對象 if(!self::$c instanceof self){ self::$c = new self; } return self::$c; } // 這裏寫各類對數據庫操做的方法,例如增刪改查 // 關閉數據庫 function __destruct() { $this->db->close(); } }
調用方法sql
$db = DB::init(); // 下面跟着要調用的操做數據庫方法 例如 $res = $db->queryall();