• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-25) 16次浏览 已收录 0个评论
文章目录[隐藏]

模仿网友写的一个单例模式实现的数据库连接,在构造函数中,成功实例化了,并把实例化的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>

回复内容:

本&文来源gao@daima#com搞(%代@#码网@

模仿网友写的一个单例模式实现的数据库连接,在构造函数中,成功实例化了,并把实例化的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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:单例模式实现数据库连接出错
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址