单例模式连接数据库

  类的单例模式只需要执行一次数据库连接,可以防止数据库的多次连接给服务器造成负担

  PHP示例代码

  

<?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(); 
    }
}

  调用方法

  

$db = DB::init();
// 下面跟着要调用的操作数据库方法 例如
$res = $db->queryall();

猜你喜欢

转载自www.cnblogs.com/zhangcheng001/p/11253849.html