Home >Backend Development >PHP Tutorial >Why Does PHP's Strict Mode Warn 'Only Variables Should Be Passed by Reference'?
Strict Standards: Understanding the "Only Variables Should Be Passed by Reference" Warning
In PHP, strict mode enforces certain programming practices to improve code quality and consistency. One such practice is avoiding passing non-variable values by reference. This question explores the reasons behind this warning and provides solutions to avoid it.
The Issue: Reference Parameters and Return Values
Consider the following code snippet:
$el = array_shift($instance->find(..))
This code triggers the strict standards warning "Only variables should be passed by reference." However, the following code does not:
function get_arr(){ return array(1, 2); } $el = array_shift(get_arr());
To understand this behavior, we need to delve into PHP's reference handling. When a reference is passed to a function, any changes made to the variable referenced by that parameter are reflected in the original variable. In the first code snippet, $instance->find(...) returns an array, which is not a variable. Passing this array by reference triggers the warning.
Understanding the Exception
However, this exception can be misleading. In the second code snippet, the function get_arr() returns an array, which implies that a reference can be passed to it. However, the function itself does not use a reference parameter, so the warning is avoided.
Solutions to Avoid the Warning
To eliminate the warning, there are two options:
Example:
function get_arr(){ return array(1, 2); } $inter = get_arr(); $el = array_shift($inter);
By using the intermediate variable $inter, we avoid passing the return value of get_arr() directly by reference, resolving the strict standards warning.
The above is the detailed content of Why Does PHP's Strict Mode Warn 'Only Variables Should Be Passed by Reference'?. For more information, please follow other related articles on the PHP Chinese website!