问题描述
我正在将基于Mysql的 PDO连接与 PDOStatement (::prepare()
; ::execute()
)结合使用,并且我已经处理了以前开发人员的一些代码,在方法中使用 PDOStatement::closeCursor()
.
I'm utilizing a Mysql based PDO connection with PDOStatement (::prepare()
; ::execute()
) and I've run over some code from a previous developer that utilizes PDOStatement::closeCursor()
in a method.
无论如何,该语句在函数末尾都未设置:
The statement is unset at the end of the function anyway:
public function fooBar($identifier)
{
...
/** @var $dbc PDO */
$dbc = $conn->getConnection();
$stmt = $dbc->prepare('SELECT orderType, orderComment, payload FROM cart WHERE identifier = :identifier');
$stmt->execute(array('identifier' => $identifier));
$stmt->setFetchMode(PDO::FETCH_OBJ);
$cart = $stmt->fetch();
$stmt->closeCursor();
...
return $result;
}
在我的心智模型中,我会说这里无论如何都清除了PDOStatement,因为我期望该对象负责此内务处理(封装基础知识).因此,对我来说,调用PDOStatement::closeCursor()
似乎是多余的,因为这可能不完全是这里想要的:由于该语句不再被重复使用,因此我根本不需要关闭游标.
In my mental model, I'd say that the PDOStatement is cleared here anyway, as I exepect the object to take care of this housekeeping (encapsulation basics). Therefore calling PDOStatement::closeCursor()
looks supferfluous to me, especially, as this might not be exactly what is wanted here: As the statement is not to be re-used, I don't need to close the cursor at all.
Stackoverflow上的现有材料
另一个问题何时应为PDO语句使用closeCursor()?没有被接受的答案,我不会怀疑关于,因为它们全都如鱼得水.
Another question When should I use closeCursor() for PDO statements? has no accepted answer which I don't wonder about because it's all wishy-washy.
在 重复使用PDO语句var会使进程崩溃 ,其中有,取消设置变量并不能消除所有错误(内存损坏错误)的方式:
In Reusing PDO statement var crashes the process there is a comment made that unsetting a variable does not get all errors (memory corruption bugs) out of the way:
但是我不知道对于范围将消失的局部变量来说是否也是如此.我也不使用mod_php
作为SAPI.
However I don't know if this is also true for local variables whose scope is to be gone. I also don't use mod_php
as SAPI.
推荐答案
pdo_mysql_stmt_dtor()
运行与相同的清除操作pdo_mysql_stmt_cursor_closer()
,因此只要显式未设置语句对象或超出范围,该操作将始终执行.
pdo_mysql_stmt_dtor()
runs the same cleanup operations as pdo_mysql_stmt_cursor_closer()
, so as long as the statement object is either explicitly unset or goes out of scope, the operations will always be performed.
因此,如果该语句无论如何都将被销毁,则不必严格地调用closeCursor()
.就个人而言,我还是会这样做,因为我希望明确易读,但这取决于个人的风格偏好.
It is therefore not strictly necessary to call closeCursor()
if the statement is about to be destroyed anyway. Personally I would do it anyway as I like to be explicit for readability, but that comes down to personal stylistic preferences.
基于以上参考,只能肯定地说 关于PDO_mysql-对于其他驱动程序,可能不成立.
Based on the references above, this can only be said for certain about PDO_mysql - for other drivers this may not hold true.
这篇关于如果未设置语句对象,是否需要调用PDOStatement :: closeCursor()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!