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

Linda Hamilton
Release: 2024-10-26 20:54:02
Original
150 people have browsed it

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"
}
Copy after login

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
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!