【发布时间】:2014-08-11 15:35:37
【问题描述】:
这是我的数据库类
class DataBase{
public $_localhost = "localhost";// server name => usually is localhost
public $_user = "root"; // username for the database
public $_password = "123"; // password for the database
public $_dbname = "ecommerce"; // database name
public $db = false;
public function __construct(){
try{
$this->db = new PDO("mysql:host=".$this->_localhost.";dbname=".$this->_dbname,$this->_user,$this->_password);
$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$this->db->exec("SET NAMES utf8");
return $this->db;
}catch(PDOException $e){
echo $e->getMessage();
}
}
public function __destruct(){
$this->db = null;
}
}
现在在我的应用程序类中
class Application{
public $db;
public function __construct(){
$this->db = new DataBase();
$this->db = $this->db->db;
}
}
因为我想使用我的 destruct 函数来关闭我的连接
这是一个好方法吗?
【问题讨论】:
-
问题是:为什么?
-
旁注:在析构函数中将实例变量设置为
null是无操作的。 -
我会说不,主要是因为destructor is not always called
-
您不应为您创建的每个实例创建新的数据库连接。传递连接对象。 (关键字:依赖注入)。反正。您的代码并没有真正增加任何价值。在发送请求后,PHP 将自行处理连接。如果您有一个长时间运行的进程或使用一些疯狂的数据库驱动程序(这里不是这种情况),则通常需要手动关闭连接。
-
@watcher 好吧,这不是问题,因为数据库连接总是在关闭时被破坏。并且只要脚本处于正常的运行时阶段并且只要没有保留周期,析构函数的行为就是确定性的......
标签: php oop connection