码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2014-11-05 13:13:47      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:io   ar   os   sp   数据   on   问题   cti   bs   

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  对象,想请问下,问题出在哪里?

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


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

标签:io   ar   os   sp   数据   on   问题   cti   bs   

原文地址:http://my.oschina.net/nixus/blog/340970

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!