rfc:concatenation_precedence

This is an old revision of the document!


PHP RFC: Change the precedence of the concatenation operator

Introduction

It's been a long standing issue that an expression like echo "sum: " . $a + $b; evaluates from left to right as echo ("sum: " . $a) + $b; instead of an intuitively expected and desired behavior of the addition having a higher precedence: echo "sum :" . ($a + $b);.

This RFC aims to change that behavior to be less error-prone and more intuitive.

Proposal

Currently the precedence of '.', '+' and '-' operators are equal. Any combination of these operators are simply evaluated left-to-right.

This is counter-intuitive though: you rarely want to add or subtract concatenated strings which in general are not numbers. However, given PHPs capability of seamlessly converting an integer to a string, concatenation of these values is desired.

Thus, the RFC proposes to give '.' an inferior precedence to '+' and '-', so that additions and subtractions are always performed before the concatenation.

Backward Incompatible Changes

Every unparenthesized expression featuring an '-' or '+' after a '.' will change behavior. As an example, the expression "3" . "5" + 7 will now be equal to 312 instead of previously 42.

While this is a subtle behavior change in that it will give different outputs without notice or warning, it is trivially possible to statically analyze the code and find all instances where this happens. As to my knowledge these occurrences are quite rare as it almost always is an error in the current form, rendering the impact minimal.

Proposed PHP Version(s)

The next 7.x (currently PHP 7.4).

Or, alternatively as a gentler upgrade, we may choose to fail hard in PHP 7.4, i.e. failing the compilation if an unparenthesized expression containing an '.' before a '+' or '-'. And only do the actual proposed change in PHP 8.

Proposed Voting Choices

“Change behavior in PHP 7.4”, “Fail in PHP 7.4 and change in PHP 8”, “Neither”.

The RFC requires a 2/3 majority for “Change behavior in PHP 7.4”. For the “Fail in PHP 7.4 and change in PHP 8” option to pass a combined 2/3 majority of “Change behavior in PHP 7.4” and “Fail in PHP 7.4 and change in PHP 8” is required.

Patch

The patch for the change itself is trivial, requiring small changes in the zend_ast.c and zend_language_parser.y to change the precendences. I'll add it later.

rfc/concatenation_precedence.1553767075.txt.gz · Last modified: 2019/03/28 09:57 by bwoebi