Home >Backend Development >PHP Tutorial >Why Does PHP's Strict Mode Warn 'Only Variables Should Be Passed by Reference'?

Why Does PHP's Strict Mode Warn 'Only Variables Should Be Passed by Reference'?

DDD
DDDOriginal
2025-01-01 13:55:19486browse

Why Does PHP's Strict Mode Warn

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:

  1. Modify the Method Signature: Change the signature of the method that takes a reference parameter to no longer use it.
  2. Use an Intermediate Variable: Create an intermediate variable to hold the return value of the method that does not use a reference parameter. Then, pass the intermediate variable by reference.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn