mysqli单例模式连接数据库

<?php
define("HOST",'localhost');
define("USERNAME",'root');
define("PASSWORD",'root');
define("DBNAME",'dianying');
//单例模式连接数据库  使用mysqli
class lianjie
{
    private static $instance;
    private static $config;
    private $dbase = [
        'host' => HOST,
        'username' => USERNAME,
        'password' => PASSWORD,
        'dbname' => DBNAME,
    ];

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function conn()
    {
        self::$config = new mysqli($this->dbase['host'], $this->dbase['username'], $this->dbase['password']);
        self::$config->query('set name utf8');
        self::$config->select_db($this->dbase['dbname']);
        return self::$config;
    }

}
$obj = lianjie::getInstance();
$db = $obj->conn();
// $sql = 'select * from xinwen LIMIT 10';
// $row = $db->query($sql);
// $data = [];
// while ($tmp = $row->fetch_assoc()) {
//     $data[] = $tmp;
// }
// echo '<pre>';
// print_r($data);
// echo '</pre>';

 

posted @ 2020-07-14 18:33  za_szybko  阅读(290)  评论(0编辑  收藏  举报