DEV Community

Cover image for Arrow Functions in PHP

Arrow Functions in PHP

rishirajpurohit profile image Rishiraj Purohit ・2 min read

Inspired from Javascript's arrow function, I guess?

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 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);

$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


Editor guide
stegriff profile image
Stephen Griffiths

It would be really great if they implemented the arrow functions RFC!

I came across it today because I'm a .Net+JS dev helping a colleague to write a PHP app talking to our API. And I knew he would need to do something like .Where from LINQ or .filter from JS.

So I found the PHP functions like array_filter, but with the long closures syntax it's just so much code! And like you say, you need the use () clause. It's messy. Arrow functions would be brilliant in PHP.

Thanks for the post!