本文實(shí)例講述了PHP實(shí)現(xiàn)單例模式建立數(shù)據(jù)庫連接的方法。分享給大家供大家參考,具體如下:
理解php單例模式
一、什么是單例
wiki百科:單例模式,也叫單子模式,是一種常用的軟件設(shè)計(jì)模式。 在應(yīng)用這個模式時,單例對象的類必須保證只有一個實(shí)例存在。 許多時候整個系統(tǒng)只需要擁有一個的全局對象,這樣有利于我們協(xié)調(diào)系統(tǒng)整體的行為。
二、為什么用單例
實(shí)際項(xiàng)目中像數(shù)據(jù)庫查詢,日志輸出,全局回調(diào),統(tǒng)一校驗(yàn)等模塊。這些模塊功能單一,但需要多次訪問,如果能夠全局唯一,多次復(fù)用會大大提升性能。這也就是單例存在的必要性。
三、單例模式的好處
1:減少頻繁創(chuàng)建,節(jié)省了cpu。
2:靜態(tài)對象公用,節(jié)省了內(nèi)存。
3:功能解耦,代碼已維護(hù)。
四、如何設(shè)計(jì)單例
通過上面的描述,單例的核心是,實(shí)例一次生成,全局唯一,多次調(diào)用。因此在單例模式必須包含三要素:
1:私有化構(gòu)造函數(shù),私有化clone。也就是不能new,不能clone?!疚ㄒ弧?/p>
2:擁有一個靜態(tài)變量,用于保存當(dāng)前的類?!疚ㄒ蝗绾伪4妗?/p>
3:提供一個公共的訪問入口?!究梢栽L問】
五、建立數(shù)據(jù)庫連接
PS:功能上不太完整,以后再補(bǔ)充**__**
/** * 單例模式連接數(shù)據(jù)庫--面向?qū)ο? * */ //final關(guān)鍵字阻止此類被繼承 final class sql2 { static $instance; static $connect; protected $result; //protected關(guān)鍵字阻止此類在外部進(jìn)行實(shí)例化 protected function __construct($host, $user, $password) { self::$connect = @new mysqli($host, $user, $password); if (self::$connect->connect_errno) { die(iconv('gbk', 'utf-8', self::$connect->connect_error) . '(' . self::$connect->connect_errno . ')'); } } //protected關(guān)鍵字阻止此類在外部進(jìn)行克隆 protected function __clone() { } //當(dāng)對象被銷毀時關(guān)閉連接 function __destruct() { self::$connect->close(); } //獲取實(shí)例 static function getInstance($host, $user, $password) { self::$instance = self::$instance ?: new self($host, $user, $password); return self::$instance; } //選擇數(shù)據(jù)庫 function set_db($db) { if (!self::$connect->select_db($db)) { die(iconv('gbk', 'utf-8', self::$connect->error) . '(' . self::$connect->errno . ')'); } } //執(zhí)行SQL語句 function query($query) { if (!($re = self::$connect->query($query))) { die(iconv('gbk', 'utf-8', self::$connect->error) . '(' . self::$connect->errno . ')'); } $this->result = $re; return $re; } //以數(shù)組形式返回查詢結(jié)果 function fetch_arr($query) { $re = $this->query($query); $res = []; while ($row = $re->fetch_assoc()) { $res[] = $row; } return $res; } //獲取記錄數(shù) function get_row() { return $this->result->num_rows; } } $ins = sql2::getInstance('127.0.0.1', 'root', 'root'); $ins->set_db('houtai'); $re = $ins->fetch_arr('select * from user '); //var_dump($re); $ins->get_row();
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:宜賓 黃南 銅川 婁底 鎮(zhèn)江 南陽 湛江 寶雞
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP實(shí)現(xiàn)單例模式建立數(shù)據(jù)庫連接的方法分析》,本文關(guān)鍵詞 PHP,實(shí)現(xiàn),單例,模式,建立,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。