Arrow Functions in PHP 7.4







Arrow functions, also called short closures , are a good way to write clean code in PHP. This form of writing will be useful when passing closures to functions like array_map



or array_filter



.







Example:







 //   Post $posts = [/* โ€ฆ */]; $ids = array_map(fn($post) => $post->id, $posts);
      
      





Previously, you had to write like this:







 $ids = array_map(function ($post) { return $post->id; }, $posts);
      
      





Briefly:









The stereotyped way of writing the example above:







 $ids = array_map(fn(Post $post): int => $post->id, $posts);
      
      





Two more important things:









If you want to return a value by reference, use the following syntax:







 fn&($x) => $x
      
      





Arrow functions implement the same functionality that you expect from normal closures, they only contain one expression.







No multiline



You read that right: short circuits can contain only one expression. This means that you cannot have multiple lines in them.







The argument is this: the goal of short circuits is to reduce verbosity. fn



, definitely shorter than function



in every sense. Skipping the function



and return



keywords does not change anything, but allows you to make the code more readable.







Do you agree with this opinion? At the same time, with the new syntax for single-line functions, there are many multi-line ones that would not be inhibited by such an upgrade.







Hopefully in the future, there will be an RFC with a short announcement and multi-line functions, but so far these are just my dreams.







Variables from the outer scope



Another significant difference between short and normal faults is that the former do not require the use of the use keyword to access data from an external scope.







 $modifier = 5; array_map(fn($x) => $x * $modifier, $numbers);
      
      





It is important to note that you cannot modify these variables. Values โ€‹โ€‹are related by value, not by reference. This means that you can modify the $modifier



inside a short circuit, but this will not affect the $modifier



variable outside.







The only exception is the $this



, which will work just like in the normal version:







 array_map(fn($x) => $x * $this->modifier, $numbers);
      
      





Future opportunities



I already mentioned the multi-line short circuit idea above. Another useful suggestion is to allow the use of short syntax in classes, for example for getters and setters:







 class Post { private $title; fn getTitle() => $this->title; }
      
      





In general, arrow functions are a very good feature, although there is still room for improvement.







Do you have any thoughts on this?








All Articles