【发布时间】:2019-04-07 23:26:51
【问题描述】:
我正在尝试编写一些包含多个类的代码,这些类稍后会有很多数据库连接/查询。
我的问题是,PDO 是否会在执行以下行后立即连接到数据库,并且会一直保持连接直到关闭?
$pdo = new PDO($dsn, $user, $pass, $options);
或者它等到我们执行以下操作才能连接,例如:
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
// Closing connection
$stmt = null;
如果在我们执行new PDO() 时没有立即连接,那么我可以轻松地将$pdo 变量设为全局变量并在每个类中使用它,否则我必须在每个类中分别使用__construct() 方法连接,然后在__destruct() 方法上关闭连接。 (我仍然不确定这是否是获得更好性能的最佳方式)
附:我们是否还需要设置$pdo = null 来关闭连接?还是$stmt = null就够了?
【问题讨论】:
-
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.php.net/manual/en/pdo.connections.php -
“我仍然不确定这是否是获得更好性能的最佳方式” ????它不是。将连接作为依赖项传递给您的类构造函数
-
@Phil 你能举个例子吗?