首页 / PHP / 单例模式实现数据库连接出错
单例模式实现数据库连接出错
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了单例模式实现数据库连接出错,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2188字,纯文字阅读大概需要4分钟。
内容图文
![单例模式实现数据库连接出错](/upload/InfoBanner/zyjiaocheng/237/758d4c7c876346cabc963999bca3ff49.jpg)
但是在下面的函数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
要改成static
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;
}
附加一篇鸟哥写的单例模式文章
http://www.laruence.com/2011/03/18/1909.html
内容总结
以上是互联网集市为您收集整理的单例模式实现数据库连接出错全部内容,希望文章能够帮你解决单例模式实现数据库连接出错所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。