您好,欢迎访问一九零五行业门户网

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

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

回复内容: 模仿网友写的一个单例模式实现的数据库连接,在构造函数中,成功实例化了,并把实例化的mysqli赋值给了$_instance
但是在下面的函数getinstance中,获取到的值,却是$db_config
请教大家一下,是哪里错了?代码还有哪些地方需要改进?谢谢!
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); }}

也是一个渣渣,你可以参考一下这个
http://www.jellybool.com/post/php-database
在构造函数里, 你的代码已经把mysqli赋值给 self::$_instance了getinstance要改成 staticpublic static function getinstance() { if (self::$_instance == null) { new self; } file_put_contents('2.txt', var_export(self::$_instance,true), file_append); return self::$_instance; }
附加一篇鸟哥写的单例模式文章
http://www.laruence.com/2011/03/18/1909.html
其它类似信息

推荐信息