Andrew Heath Andrew Heath - 7 months ago 24
PHP Question

PDO pass by reference notice?

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?

Answer

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:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color");
$tempColor = NULL; // assigned here
$stmt->bindParam(':color',$tempColor);
$tempColor = $someClass->getColor(); // but reassigned here
$stmt->execute();

That won't be possible with a function return.