PHP 7.4 arrow functions

Neste artigo você vai ver:

PHP will finally have the syntax for arrow functions. The voting for this feature was finished on May 2nd, 2019 and will probably be released on version 7.4, around late November 2019.

But what are arrow functions? And how they work? An arrow function is “just” a syntactic sugar for defining closures in PHP. Before arrow functions, functions like map, filter, reduce, and many others that receive a function as a parameter, had to be described as the following:

<p> CODE: https://gist.githubusercontent.com/williamokano/0083fc7bec2503f1ad26f8ff63661626.js</p>

array_map without an arrow function

Now, with the new syntax (well, at least the syntax on the day I’m writing — May 3rd, 2019), the code can be written as the following:

<p> CODE: https://gist.githubusercontent.com/williamokano/19151c2c4fd7446e8d26cfff552da8a4.js</p>

array_map with an arrow function

What are the real differences, or benefits?

  1. The code is more readable (at least in my humble opinion);
  2. The code is shorter, which means less boilerplate code;
  3. The arrow function captured the outside variables (variable binding) without explicitly defining it using the use keyword. Again, increasing readability.

But there is a trick. With anonymous functions, when binding a variable, you can change the value if the variable is bound using &. This is not possible, at least yet, using arrow functions. Look at the following code:

<p> CODE: https://gist.githubusercontent.com/williamokano/19151c2c4fd7446e8d26cfff552da8a4.js</p>

Example of variable binding using an arrow function and anonymous functions

In my humble opinion, this is a great plus for the language. I haven’t yet tested the performance between the new and the old syntax, but I think that will be no big difference; if any.

Two things to keep in mind:

  1. The version is not yet finished, and, although the code is already merged on the master branch of PHP, which means it will be released, it can be changed along the year;
  2. The binding variables are only by-value, and can’t be changed inside the arrow function; this part still open to discussion and can change in the future.

To further study, check out the RFC about arrow functions https://wiki.php.net/rfc/arrow_functions_v2

5cdb22ac77d529d60711d5bf_william
Back-end Developer
Apaixonado por desenvolvimento, mas não dispensa comidas deliciosas e oportunidades de dormir.

Artigos relacionados

Este site utiliza cookies para proporcionar uma experiência de navegação melhor. Consulte nossa Política de Privacidade.