时间:2021-07-01 10:21:17 帮助过:14人阅读
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