PDO 通过参考通知?
这:
$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindParam(':color', $someClass->getColor());
$stmt->execute();
产生这样的:
运行时通知
只能传递变量 参考
,但它仍然执行。
这:
$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = $someClass->getColor();
$stmt->bindParam(':color',$tempColor);
$stmt->execute();
毫无怨言地运行。
我不明白有什么区别?
This:
$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$stmt->bindParam(':color', $someClass->getColor());
$stmt->execute();
yields this:
Runtime notice
Only variables should be passed by
reference
though it still executes.
This:
$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = $someClass->getColor();
$stmt->bindParam(':color',$tempColor);
$stmt->execute();
runs without complaint.
I don't understand the difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
PDOStatement::bindParam()
的描述表明它将 PHP 变量绑定到问题标记或命名占位符。由于您试图传递类的方法(即使该方法确实返回一个值),它仍然不是变量名,因此会出现警告。您可能需要查看PDOStatement::bindValue()
来确保您的代码面向未来。The description of
PDOStatement::bindParam()
states that it binds a PHP variable to a quesitonmark or named placeholder. Since you are trying to pass a class's method (even though that method does return a value) it is still not a variable name, hence the warning. You might want to look atPDOStatement::bindValue()
to future-proof your code.bindParam 的第二个参数是一个变量引用。由于函数返回无法被引用,因此它无法严格满足bindParam参数的需求(PHP将与您一起工作,并且只会在此处发出警告)。
为了获得更好的想法,这里有一个示例:此代码将产生与第二个示例相同的结果:
这对于函数返回是不可能的。
The second parameter of bindParam is a variable reference. Since a function return cannot be referenced, it fails to strictly meet the needs of the bindParam parameter (PHP will work with you though and will only issue a warning here).
To get a better idea, here's and example: this code will produce the same results as your second example:
That won't be possible with a function return.
如果您想避免将值分配给变量,您可能最好尝试:
正如其他人提到的,导致错误的原因是PDO::statement->bindParam 期望参数 2 是通过引用传递的变量。
If you want to avoid assigning the value to a variable, you might be better off trying:
As others have mentioned, the error is caused because PDO::statement->bindParam expects param 2 to be a variable passed by reference.
如果您确实想绑定一个值而不是引用,可以使用 PDOStatement::bindValue 然后你的代码将如下所示:
If you really want to bind a value instead of a reference, you can use the PDOStatement::bindValue and then you code would look something like this: