Home  >  Article  >  Backend Development  >  Why do Parentheses Fix \"Only Variables Should Be Passed by Reference\" Errors in PHP Function Calls?

Why do Parentheses Fix \"Only Variables Should Be Passed by Reference\" Errors in PHP Function Calls?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 20:54:02151browse

Why do Parentheses Fix

Parentheses and the Meaning of Function Call Results

Consider the following example:

<?php
function get_array() {
    return array();
}

function foo() {
    return reset(get_array()); // Error: "Only variables should be passed by reference"
}

In this code, the error occurs because the result of the function call is not a reference. However, if the result is wrapped in parentheses, the error disappears:

function foo() {
    return reset((get_array())); // OK
}

What is happening here?

Despite the absence of documentation explicitly describing this behavior, it can be understood by examining the PHP grammar and compiler implementation.

Effect on Parsing

The parentheses cause PHP's parser to interpret the result of the function call as an expression instead of a variable. This affects how the compiler interprets the code, particularly the opcode used to send variables to functions.

Reference Count and Zend Engine Optimization

The Zend Engine, PHP's core engine, allows non-reference variables with a reference count of 1 to be used where references are expected. In the example above, the returned array is a new object with a reference count of 1. This allows the Zend Engine to optimize the code and avoid the error message.

Limitations

It's important to note that this behavior is considered a bug and should not be relied upon. The reference count of the function call result may change in future PHP versions, breaking code that depends on this behavior.

Alternative Solution

To avoid relying on this potentially unstable behavior, explicitly assign the result of the function call to a variable:

function foo() {
    $result = get_array();
    return reset($result);
}

The above is the detailed content of Why do Parentheses Fix \"Only Variables Should Be Passed by Reference\" Errors in PHP Function Calls?. 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