使用單例模式建立一個數據庫連接簡單示例


<?php
/*
 *describe:單例模式 數據庫類
單例模式的必要條件
(1)私有的構造方法-為了防止在類外使用new關鍵字實例化對象
(2)私有的成員屬性-為了防止在類外引入這個存放對象的屬性
(3)私有的克隆方法-為了防止在類外通過clone成生另一個對象
(4)公有的靜態方法-為了讓用戶進行實例化對象的操作
*/
header("content-type:text/html;charset=utf-8");

class DbSingleton
{
    private $charset = "utf8";         //字符串編碼

    //私有的成員屬性-為了防止在類外引入這個存放對象的屬性
    private static $instance = NULL;   //存儲對象

    //私有的構造方法-為了防止在類外使用new關鍵字實例化對象
    private function __construct($host, $username, $password, $dbname, $port)
    {
        $link = mysqli_connect($host, $username, $password, $dbname, $port);
        if (!$link) {
            die("連接錯誤: " . mysqli_connect_error());
        }
        // 修改數據庫連接字符集為 utf8
        mysqli_set_charset($link, $this->charset);
        return $link;
    }

    //私有的克隆方法-為了防止在類外通過clone成生另一個對象
    private function __clone()
    {
    }

    //公有的靜態方法-為了讓用戶進行實例化對象的操作
    public static function getInstance($host, $username, $password, $dbname, $port)
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($host, $username, $password, $dbname, $port);
        }
        return self::$instance;
    }
}

//測試:
//$host     = '127.0.0.1';
//$username = 'root';
//$password = '123456';
//$dbname   = 'test';
//$port     = 3306;
//$db = DbSingleton::getInstance($host, $username, $password, $dbname, $port);
//var_dump($db);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM