Search code examples
phparrow-functions

Does PHP Support Arrow Function Syntax?


After complaining about the tumultuous task of writing the keyword function over and over, I asked someone about an easier way. The person said that PHP is going to have arrow function syntax similar to es6.

const foo = (x, y) => {
    return x + y;
};

As I continued to look into this, I have not been able to find many examples online.

Can someone of the right caliber please expound upon this?

At this point, I am also really interested in how this would fit into the OOP aspect of PHP.


Solution

  • Original answer from February 2018:

    This appears to be the syntax described in https://wiki.php.net/rfc/arrow_functions. It does have an experimental implementation.

    In the arrow functions proposal, it is mentioned that it's an alternative to the "short closures" proposal, https://wiki.php.net/rfc/short_closures

    As of February 2018, the current versions of PHP are 7.1.4 / 7.2.2.

    I can't find any confirmation that either proposal has been approved. The former is in the "Under Discussion" state, the latter is "Declined / Withdrawn in favor of http://wiki.php.net/rfc/arrow_functions". I think it's too soon to know whether it will be adopted in any future version of PHP.


    Update December 2019:

    The feature has been released in PHP 7.4, according to https://www.php.net/manual/en/migration74.new-features.php

    Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding.

    <?php
    $factor = 10;
    $nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
    

    But the usage has not been updated yet in the PHP manual page about Anonymous Functions

    Here's a blog going into detail: https://stitcher.io/blog/short-closures-in-php