PHP arrow functions: Solution approved

The PHP team recently approved the solution for short arrow functions proposed by Nikita Popov, Levi Morrison and Bob Weinand in an RFC.

Anonymous functions in PHP can be quite verbose, even if they perform only a simple operation. This is partly due to a large amount of syntactic boilerplate and partly due to the need to manually import used variables. This makes code sometimes difficult to read and understand.

PHP RFC: Arrow Functions 2.0

An RFC suggested a shorter syntax for this pattern. With 51 votes in favor (8 against), the “Adding arrow functions as described in PHP 7.4” was now approved in the poll.

An example from the previous version , which describes the declaration effort quite well.

function array_values_from_keys ( $arr , $keys ) {
return array_map ( Function ( $x ) use ( $arr ) 
  { 
    return $arr [ $x ] ; 
  }, $keys );
}

The closure performs a single operation and consists of 8 characters, but requires 30 other characters (except spaces). This means that about 79% of the code of closure is overhead. These additional characters are also referred to as “boilerplate”. The RFC proposed arrow functions to reduce the number of boilerplates by a shorter syntax and implicitly import used variables from the outer area. The use of arrow functions is reduced to the following: $arr[$x].

function array_values_from_keys ( $ arr , $ keys ) {
return array_map ( fn ( $ x ) => $ arr [ $ x ] , $ keys ) ;
}

The question of short closures has already been discussed extensively in the past. In a previous short-closing RFC, the voting was rejected. The present proposal, which found a majority, attempted to resolve some of the concerns raised with a different choice of syntax that would not be subject to the limitations of the previous proposal.

In the RFC, a detailed discussion of various syntax alternatives and binding semantics was conducted. The authors of the RFC note that short-circuiting is unfortunately an issue that is unlikely to find a “perfect” solution due to significant syntax and implementation limitations. The proposal, which has now been agreed, makes the choice that the initiators of the RFC consider to be “least bad”. The detailed version of the now mostly agreed proposal can be found on the PHP wiki page.

Recent Articles

spot_img

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here