This is an old revision of the document!
PHP RFC: Change the precedence of the concatenation operator
- Version: 0.9
- Date: 2019-03-28
- Author: Bob Weinand, bobwei9@hotmail.com
- Status: Draft
- First Published at: http://wiki.php.net/rfc/concatenation_precedence
Introduction
It's been a long standing issue that an (unparenthesized) expression with '+', '-' and '.' evaluates left-to-right.
echo "sum: " . $a + $b; // current behavior: evaluated left-to-right echo ("sum: " . $a) + $b; // desired behavior: addition and subtraction have a higher precendence 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)
PHP 8, with a deprecation notice in PHP 7.4 upon encountering an unparenthesized expression containing an '.' before a '+' or '-'.
Proposed Voting Choices
“Change the precedence in PHP 8”, “No”
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. The emission of deprecation is a bit more contrived... I'll add it later.