【发布时间】:2019-06-23 22:52:48
【问题描述】:
我创建了一个连接到数据库的类。然后,所有其他类都可以使用此类中的 connect 函数来打开与 DB 的连接。在函数结束时,我返回结果。那么返回结果后如何关闭连接呢?
<?php
class DbhPdo {
private $servername;
private $username;
private $pwd;
private $dbname;
protected function connect() {
$this->servername = "localhost";
$this->username = "someUser";
$this->pwd = "somePswd";
$this->dbname = "someDB";
$this->charset = "utf8mb4";
try{
$dsn = "mysql:host=" . $this->servername . ";dbname=" . $this->dbname . ";charset=" . $this->charset;
$pdo = new PDO($dsn, $this->username, $this->pwd);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e) {
echo "Message: " . $e->getMessage();
}
}
}
如果我在返回后设置以下内容,则永远不会调用它来关闭连接:
$pdo = null;
或者 PDO 是否会自动关闭此连接,因为它在执行命令之后 - return $pdo?
或者我是否必须关闭扩展连接的类中的连接?
以下是上述类的扩展类,但我也在这个类中返回结果,所以我也不能在这里将stmt设置为null:
<?php
require_once('dbh.pdo.inc.php');
class LoginPdo extends DbhPdo {
public $name;
public $pass1;
public $hashed;
public $salted;
protected function getSomething($name) {
try{
$stmt = $this->connect()->query("select something from table where name ='" . $name . "'");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}catch (PDOException $e){
echo 'Message: ' . $e->getMessage();
}
}
}
留下了开始这个的原始类:
try{
$this->result = $this->getSomething($this->name);
echo json_encode($this->result);
$this->result = null;
}catch (PDOException $e){
echo 'Message: ' . $e->getMessage();
}
设置 $this->result = null 是否会关闭连接?如果是这样,那我就不明白了。有人可以向我解释吗?还是在设置 $pdo = null 是我需要关闭连接的地方时我是否理解正确?
如果是这样,那么在return $pdo执行后如何将其设置为null?
提前致谢
更新: 以防万一其他人希望能够验证连接是否已关闭,我采取了以下步骤来确认@Don'tPanic cmets 以跟踪常规日志文件:
mysql -u root -p
show variables like '%log%';
set global general_log=ON;
tail -f /usr/local/mysql/data/<your log file's name>.log
然后显示连接,因为我使用 PostMan 发布以下查询被立即打开和关闭:
190130 11:00:17 2581 Query show variables like '%log%'
190130 11:02:14 2582 Connect root@localhost on <table name>
2582 Query select * from something where name ='whatever'
2582 Quit
这是通过遵循@Don'tPanic 回答在 DbhPdo 类中添加一个新函数来完成的:
protected function disconnect() {
$this->pdo = null;
}
然后我添加了 $this->pdo = null; echo json_encode($this->result);
之后感谢所有的cmets
【问题讨论】:
-
您不会将连接存储在变量中,因此很难将其设置为 null。如果将连接设置为类的属性 (
$this->pdo),则可以添加一个方法将该属性设置为 null 以关闭连接。 -
其实你现在的方式,如果你用其他方法也用
connect()这样的话,我想你会创建多个连接。 -
$this->charset = "utf8mb4";在哪里定义为属性?参考DbhPdo类。 -
@Jaquarh,感谢您的回复,我不敢相信我在使用它几个月后没有收到错误,但我添加了 private $charset;与其他变量。
-
@Don'tPanic,你是说我需要添加私有 $pdo,但是我应该在哪里设置 $this->pdo = null?据我了解,$this->pdo 将连接返回到 $stmt = $this->connect()->query()。如果我将其设置为 null,那么 $stmt 将如何执行。在您的第二条评论中,我相信您是正确的,这就是为什么我想知道是否有办法从连接函数中关闭连接?或者在我回显 json_encode() 之后,我是否必须进入每个原始调用以连接并关闭 $this->pdo = null?
标签: php pdo database-connection