Why Does Parenthesizing a Function Call in PHP Avoid a Reference Error?

Susan Sarandon
Release: 2024-10-26 22:35:30
Original
165 people have browsed it

Why Does Parenthesizing a Function Call in PHP Avoid a Reference Error?

Parentheses and Function Call Semantics in PHP

In PHP, enclosing the result of a function call in parentheses can alter the semantics of the result, as demonstrated by the following code:

<code class="php">function get_array() {
   return array();
}

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

   return reset((get_array()));
   //           ^ OK
}

foo();</code>
Copy after login

This puzzling behavior has no explicit explanation in the official documentation, leaving developers uncertain about its underlying mechanics.

Analysis

The key to understanding this behavior lies in the PHP language's ambiguity in parsing function call arguments. When parentheses are added around the function call as in (get_array()), PHP treats it not as a function call, but as an expression. This distinction is crucial because the opcode used to send variables (ZEND_SEND_VAR_NO_REF) has different behavior for function calls compared to expressions.

When it encounters a non-function call expression, ZEND_SEND_VAR_NO_REF performs the following checks:

  1. The argument is not a function call.
  2. The argument is either a reference or has a reference count of 1.

In the provided example, the parenthesized function call ((get_array())) satisfies both conditions:

  1. It is not recognized as a function call due to the extra parentheses.
  2. The returned array has a reference count of 1 since it is only referenced within the function call.

As a result, the opcode proceeds without throwing the "Only variables should be passed by reference" error. However, it's important to note that this behavior is considered a bug and should not be relied upon in production code.

The above is the detailed content of Why Does Parenthesizing a Function Call in PHP Avoid a Reference Error?. 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!