Re: [PHP-DEV] Re: [RFC] Arrow functions / short closures

This is only part of a thread. view whole thread
March 15, 2019 21:44 (Theodore Brown)
On Fri, March 15, 2019 at 4:45 AM Josh Di Fabio <> wrote:

> I'd certainly be on board with the fn() syntax, but the backslash > syntax has definitely grown on me. To me, all of the examples in > Theodore's email are very readable and I find that the backslash makes > it very easy to identify arrow functions when grokking. > > `array_filter($numbers, \$n => $n % 2);` > vs. > `array_filter($numbers, fn($n) => $n % 2);` > > When grokking these two pieces of code, I immediately see `\$n => $n % > 2` > as a single unit, whereas in the latter example I instinctively > (and incorrectly) interpret "fn($n)" as an expression. > > When parens are required, the difference is obviously reduced, but I > think I still prefer the backslash syntax since the LHS doesn't grok > as a function call. > > `reduce($numbers, \($x, $y) => $x + $y);` > vs. > `reduce($numbers, fn($x, $y) => $x + $y);` > > That said, I'd personally take either syntax gladly.
You have a good point about `fn()` looking like an expression. That said, since it would be a keyword IDEs will highlight it differently which should help avoid confusion. Regarding the backslash syntax, I forgot to check how it looks with by-reference passing and returning before I sent my email. Here are those examples: ```php fn(&$x) => $x; fn&($x) => $x; // vs. \(&$x) => $x; \&($x) => $x; // unclear if passing or returning by reference \&$x => $x; // and worst of all... fn&(&$x) => $x; // vs. \&(&$x) => $x; ``` I have to admit that the `fn` prefix is a little more readable for these use cases (though I've never actually seen a real function using by-reference passing and returning at the same time). -Theodore Brown