您的位置:首页 > 博客中心 > 数据库 >

PHP单例模式实现数据库连接

时间:2022-03-14 02:00

class DB
{
    private $db_config = ‘./config.php‘;
    private static $_instance;

    private function __construct()
    {
        if (file_exists($this->db_config)) {
            require $this->db_config;
            self::$_instance = new mysqli($db_host, $db_name, $db_passwd);
        } else {
            throw new Exception(‘not found database configuration file.‘);
        }
    }
    
    /**
     * 单例方法 用户访问实例的静态方法
     *
     * @return void
     */
    public function getInstance() {
        if (self::$_instance == null) {
            self::$_instance = new self;
        }
        file_put_contents(‘2.txt‘, var_export(self::$_instance,true), FILE_APPEND);
        return self::$_instance;
    }

    /**
     * 防止对象被克隆
     *
     * @return void
     */
    private function __clone()
    {
        trigger_error(‘Clone is not allow!‘, E_USER_ERROR);
    }
}

试着用单例模式写了一个数据库连接,在执行的时候,发现通过  getInstance()  方法获取到的只是  $db_config  ,并没有获取到实例化后的   mysqli  对象,想请问下,问题出在哪里?

还有哪些地方可以做优化?


热门排行

今日推荐

热门手游