使用 PreparedStatement 解释按引用传递 PHP

Explain Passing by Reference using a PreparedStatement PHP

我有两段代码:注意 $a 变量如何从函数调用外部移动到函数调用内部。

$pst = $conn->prepare("INSERT INTO TEST (Num, N, Pos, Team) VALUES (?,?,?,?)");
$a = 99;
$pst->bindParam(1, $a);
$pst->bindParam(2, $a = "badName");
$pst->bindParam(3, $a = "whoCares");
$pst->bindParam(4, $a = "Winning Team");
$pst->execute();

$pst = $conn->prepare("INSERT INTO TEST (Num, N, Pos, Team) VALUES (?,?,?,?)");
$pst->bindParam(1, $a = 99);
$pst->bindParam(2, $a = "badName");
$pst->bindParam(3, $a = "whoCares");
$pst->bindParam(4, $a = "Winning Team");
$pst->execute();

第一个代码片段通过了,而第二个代码片段抛出经典的“仅变量应按引用传递”错误。为什么会发生这种情况?为什么这只发生在第一行——例如,这没有发生在第一个片段的第 2、3、4 行。

编辑 问题似乎与此 What is the difference between bindParam and bindValue? 类似,但仍无法解释由于在函数调用外部设置变量而导致的错误原因 - 在任一代码段中都设置了变量!

bindParam API定义如下:

boolean PDOStatement::bindParam(mixed parameter,mixed &variable[,int datatype
                            [,int length[,mixed driver_options]]])

关注

mixed &variable

1个引用应该是变量!不是常量(如字符串或数字)

2 当 $a 未定义时

value of "$a = 1" was the result of expression : 1 , so the param was 1

$a 定义后,php 似乎将参数设置为 $a(我们应该挖掘 php 的地下机制 - 编译和执行): 检查下面的代码:

function test(&$var) {
   //only reference! php will check the param
   echo $var;
}
try {
   test($a=1);// report  Only Variables should be passed by reference Error
   unset($a);  // delete $a
   test($a=2);// report again !
} catch (Exception $e) {
   echo $e->getMessage();
}