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>
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:
In the provided example, the parenthesized function call ((get_array())) satisfies both conditions:
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!