📜 ⬆️ ⬇️

PHP 7.4 will include arrow functions (abbreviated anonymous functions)

Abbreviated syntax voting for functions completed (51 “for”, 8 “against”).


It was:


$result = array_filter($paths, function ($v) use ($names) { return in_array($v, $names); }); 

It became:


 $result = array_filter($paths, fn($v) => in_array($v, $names)); 

Details under the cut


The new syntax is:


Syntax


 fn(_) => _ 

In the signature of the arrow function, as in the normal function, you can specify types, defaults, etc.


 fn(array $x) => $x; fn(): int => $x; fn($x = 42) => $x; fn(&$x) => $x; fn&($x) => $x; fn($x, ...$rest) => $rest; 

Attention! A new keyword fn , which means backward incompatibility!


Other (discarded) syntax ideas


Considered options:


  //  ,        ($x) => $x * $y //   ,     ,     { ($x) => $x + $y } //     Hack;       ($x) ==> $x * $y // ,      ($x) -> $x * $y //      $x-- > $x*$y $x --> $x * $y //    Rust,    |$x| => $x * $y 

and some others


Variable closure


Important! Unlike previous versions of php, where you had to explicitly set the lockable variables with the use operator, the switch function implicitly closes the entire parent loop.


Here are the equivalent entries:


 $y = 1; $fn1 = fn($x) => $x + $y; $fn2 = function ($x) use ($y) { return $x + $y; }; 

The $ this variable is locked in exactly the same way as any other variable. If this is undesirable behavior, you can disable it with the static keyword .


 class Test { public function method() { $fn = fn() => var_dump($this); $fn(); // object(Test)#1 { ... } $fn = static fn() => var_dump($this); $fn(); // Error: Using $this when not in object context } } 

The closure of variables in pointer functions occurs by value (unlike Go, for example). Those. changing variables inside a function will not change the variable in the parent scope.


findings


The code has become much more compact, and although not as compact as in javascript and some other languages, it will still be much nicer to write:


 $result = Collection::from([1, 2]) ->map(fn($v) => $v * 2) ->reduce(fn($tmp, $v) => $tmp + $v, 0); echo $result; //6 

Unlike some other languages, pointer functions in php do not support multiple statements separated by a symbol ; , because it (according to the authors of the RFC) contradicts the idea of ​​abbreviated syntax. Perhaps this will be revised in the future.


We will definitely discuss the switch functions in php in the Zinc Prod podcast, so be sure to subscribe.


RFC Link


')

Source: https://habr.com/ru/post/450544/


All Articles