[php-src] Issue #10196: multiple expressions operator (comma)

From: Date: Sat, 31 Dec 2022 03:45:17 +0000
Subject: [php-src] Issue #10196: multiple expressions operator (comma)
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-243295@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/10196 Author: aetonsi ### Description Hello i'd like to propose the implementation of a new (or is it?) operator: [the comma operator](https://en.wikipedia.org/wiki/Comma_operator), as already present in C, Perl, Javascript, and more. Brief description: In some situations you might find yourself needing multiple expressions in a place where one expression is expected. A simple comma operator expr1 , expr2 would evaluate expr1, then expr2, then return expr2. One could chain commas and get the very last expression: expr1, expr2, expr3, expr4 would return expr4 after evaluating all the others in sequence (it's left associative). In most of the actual use cases (borrowing from [wikipedia](https://en.wikipedia.org/wiki/Comma_operator#Uses) and [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator#examples): Conditions with side effects, Complex return statements, Avoiding a block, etc) one could avoid a comma by being more verbose. But sometimes a simple comma would be much cleaner than the verbose version. For example, in very simple closures (that could be defined with arrow functions), but with side effects. In php, arrow functions by definition return a single expression, because "Once you have multiple statements, the relative overhead of the conventional closure syntax becomes small" (see [RFC arrow_functions_v2](https://wiki.php.net/rfc/arrow_functions_v2), section "Multi-statement bodies"). That's kinda agreeable, although an arrow function is **not only** a "shorter syntax" for a closure, it also has the unique advantage of implicitly inheriting all the scope variables. An example where a comma would be very useful: ```php $x=1; $y=2; $z=3; // ... $verbose = function () use ($x, $y, $z /* ,... */) { // i may have to use() TENS of variables, JUST to run 1 more instruction sideeffect(); return $x * $y * $z /* *... */; }; $ideal = fn () => (sideeffect(), $x * $y * $z); ``` But in reality this operator is already present in php: for loops with more than 1 instruction in each expression/parameter make use of it. Example directly from the [php docs](https://www.php.net/manual/en/control-structures.for.php): ```php for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++); ``` In conclusion: - since it's a cool nifty feature - since the beloved C and Perl have it - since it can actually improve the readability of code by removing unwanted verbosity (NB: aside from a few key points, readability is subjective :) ) - since it's already implemented in for loops could we make it universally available? Have a nice day

« previous php.bugs (#243295) next »