I have a method in a class with this signature:
public static function execute($query, $data = array(), &$result = NULL, $onlyOne = true)
The point is to execute a SQL query with data (if relevant) and modify the result variable (if set to true) and finally returning only first row if the caller is interested in it only. It handles SQL errors etc. and overall is a convenience thing as I try to reduce the sql queries in the script to single line or two (checking the result).
Now I have a problem with this:
Db::execute("query with :data", array(":data" => "data"), ($row = true));
The PHP complains about the $row not being a variable:
Strict standards: Only variables should be passed by reference
As I understand the PHP scopes the scope is function-wide and not block-wide (as in C++ for example). Therefore the $row
should be a variable in my function scope and available for passing as reference (and not just a temporary inside the function call). If I declare it beforehand it works but it inflates the code somewhat. Is there a way to keep the declaration of that variable in the function call like this?
EDIT: To add to the accepted answer. The reference can be assigned any default value so I changed my signature to:
public static function execute($query, $data = array(), &$result = -1, $onlyOne = true)
which allows me to call it using:
Db::execute("query with :data", array(":data" => "data"), $row);
without pre-declaring the result variable. Inside I simply check if the $result is not -1 (or I could check if it is NULL signifying new empty variable) to fill the result in.
That's an assignment. In PHP, the result of an assignment is the value being assigned, so you're passing
true
in to your function. That argument is defined as a reference, and you can't create a reference totrue
.You'd have to do: