Arrow Functions in PHP

Arrow Functions in PHP

Inspired by Javascript's arrow function, I guess? es6-in-depth-arrow-functions

The short closures called arrow functions are one of the long-due functionalities that PHP 7.4 will bring. It is proposed by Nikita Popov, Levi Morrison, and Bob Weinand and you can read the original RFC here

Quick Example is taken from Doctrine DBAL

//old way
$this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
    return in_array($v, $names);
});

//new way with arrow function
$this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));

Let's go through the rules

  1. fn is a keyword and not a reserved function name.

  2. It can have only 1 expression and that is the return statement.

  3. No need to use return and use keywords.

  4. $this variable, the scope and the LSB scope are automatically bound.

  5. You can type-hint the arguments and return types.

  6. You can even use references & and spread operator ...

Few examples


//scope example
$discount = 5;
$items = array_map(fn($item) => $item - $discount, $items);


//type hinting
$users = array_map(fn(User $user): int => $user->id, $users);

//spread operator
function complement(callable $f) {
    return fn(...$args) => !$f(...$args);
}

//nesting
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;

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

Future Scope

  1. Multi-line arrow functions

  2. Allow arrow notation for real functions inside a class.


//valid now
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
    }
}

//maybe someday in future
class Test {
    private $foo;
    private $bar;

    fn getFoo() => $this->foo;
    fn getBar() => $this->bar;
}

My Favorite takeaways

  1. Callbacks can be shorter

  2. No need for use keyword, you can access variables.

Let me know what do you think about these updates and what are your favorite takeaways from this?

till next time, rishiraj purohit

Did you find this article valuable?

Support Rishiraj Dev by becoming a sponsor. Any amount is appreciated!