DEV Community

Freek Van der Herten
Freek Van der Herten

Posted on • Originally published at freek.dev

On using arrow functions in PHP 7.4

In PHP 7.4 a widely requested feature landed: arrow function. In this blogpost I'd like to show you how I like to use them.

Let's start with an example from the Oh Dear codebase I tweeted out a few days ago.

In Laravel 6 and PHP 7.3 you could do this:

public static function boot()
{
    static::boot();

    static::creating(
        function (Team $team) {
            return $team->webhook_signing_secret = Str::random(32);
        }
    );
}

In Laravel 7 and PHP 7.4 you can rewrite it to this:

public static function booted()
{
   static::creating(fn (Team $team) => $team->webhook_signing_secret = Str::random(32));
}

In the code snippet above, a short closure is used. It's a bit beyond the scope of this post, but in Laravel 7, the booted lifecycle method was introduced, which will, unsuprisingly, be called we the model has booted. Using that method, you can lose the static::boot(); call from the initial code snippet.

A lot of people seemed to like it. Some didn't, and that's ok. When introducing new syntax, I don't think there's a single thing where all programmars will agree on. A comment I agree on however, is the line lenght. Luckily this can be easily fixed by moving the closure itself to it's own line.

public static function booted()
{
   static::creating(
      fn (Team $team) => $team->webhook_signing_secret = Str::random(32)
   );
}

To make the line length shorter, you could opt to remove the typehint. You could even rename the $team variable to $t, this is pretty common practice in the JavaScript. Personally I live typehints and full variable names, so personally I stick to the code snippet above.

I think it would be silly to blindly switch to short closures wherever it is technically possible. The question you should keep in mind when converting a closure to a short one is: "Does this make the code more readable?". Of course, the answer is subjective. When in doubt, I recommend just asking your team members, they're the ones that will have to read your code too.

If you use PhpStorm you can easily switch between a normal and a short closurse, so you can quickly get a feel of how it reads.

convert.

Let's end by taking a look at an example where I think short closures really shine: in collection chains (thanks for the example, Liam).

Top comments (1)

Collapse
 
mdhesari profile image
Mohammad Fazel

Great article, thank you!