Home >Backend Development >PHP Tutorial >单例模式实现数据库连接出错

单例模式实现数据库连接出错

WBOY
WBOYOriginal
2016-06-06 20:41:431146browse

模仿网友写的一个单例模式实现的数据库连接,在构造函数中,成功实例化了,并把实例化的mysqli赋值给了$_instance
但是在下面的函数getInstance中,获取到的值,却是$db_config
请教大家一下,是哪里错了?代码还有哪些地方需要改进?谢谢!

<code>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);
    }
}
</code>

回复内容:

模仿网友写的一个单例模式实现的数据库连接,在构造函数中,成功实例化了,并把实例化的mysqli赋值给了$_instance
但是在下面的函数getInstance中,获取到的值,却是$db_config
请教大家一下,是哪里错了?代码还有哪些地方需要改进?谢谢!

<code>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);
    }
}
</code>

也是一个渣渣,你可以参考一下这个
http://www.jellybool.com/post/php-database

  1. 在构造函数里, 你的代码已经把mysqli赋值给 self::$_instance
  2. getInstance要改成 static
<code>public static function getInstance() {
        if (self::$_instance == null) {
            new self;
        }
        file_put_contents('2.txt', var_export(self::$_instance,true), FILE_APPEND);
        return self::$_instance;
    }
</code>

附加一篇鸟哥写的单例模式文章

http://www.laruence.com/2011/03/18/1909.html

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn