abstract:單例模式主要使用于數(shù)據(jù)庫的連接, 確保數(shù)據(jù)庫一個(gè)類只有一個(gè)實(shí)例, 并且向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。從而避免new操作消耗資源, 同時(shí)避免數(shù)據(jù)庫出現(xiàn)too many connection信息.要點(diǎn)有三個(gè): 1. 必須只有一個(gè)實(shí)例。 2. 必須自動創(chuàng)建這個(gè)實(shí)例。 3. 必須向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。<? class mysql{ &
單例模式主要使用于數(shù)據(jù)庫的連接, 確保數(shù)據(jù)庫一個(gè)類只有一個(gè)實(shí)例, 并且向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。從而避免new操作消耗資源, 同時(shí)避免數(shù)據(jù)庫出現(xiàn)too many connection信息.
要點(diǎn)有三個(gè): 1. 必須只有一個(gè)實(shí)例。 2. 必須自動創(chuàng)建這個(gè)實(shí)例。 3. 必須向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。
<? class mysql{ privete static $instance ;//保存實(shí)例 //構(gòu)造函數(shù)聲明為private, 防止直接創(chuàng)建對象 privete function __construct(){ // 實(shí)例化 } //單例方法, 判斷是否已經(jīng)實(shí)例化,只實(shí)例化一次 public static function getInstance (){ if(!isset( self::$instance )){ self ::$instance = new self(); } return self:: $instance; } //防止克隆對象 private function __clone (){ trigger_error ("not allow to clone."); } function test(){ echo "test" ; } } $conn = mysql::getInstance (); $conn->test (); ?>
更多關(guān)于php單例模式示例分享請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)其他文章!