设计模式八:单例模式
单例模式:
只有一个实例。只可以通过该实例去调用该对象其他方法。单例的最大特点是三私一公。
<?php class DBUtil{ private $conn; private static $instance = null; private function __construct() { try{ $this->conn = @ mysqli_connect('localhost','root','','testDB'); return $this->conn; }catch(Exception $e){ echo $e->getMessage(); } } /** * 防止被克隆 */ private function __clone(){} /** * 获取实例 */ public static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new DBUtil(); } return self::$instance; } public function select($sql){ return mysqli_query($this->conn,$sql); } public function first($sql) { $result = $this->select($sql); return mysqli_fetch_row($result); } public function get($sql){ $result = $this->select($sql); return mysqli_fetch_array($result); } } $db = DBUtil::getInstance(); $result = $db->get('select * from provinces'); var_dump($result);