DEV Community

Aju Chacko
Aju Chacko

Posted on

2 1

Arrow➡️ functions in php

There is a new feature in php 7.4 added called short closures or arrow functions. Below is an example of array_map() with closure and new syntax. It is much neater related to using closure when passing to functions like array_map and array_filter.

$ids = array_map(function ($post) {
    return $post->id;
}, $posts);

// A collection of Post objects
$posts = [/* … */];

$ids = array_map(fn($post) => $post->id, $posts);

// with type hinting
$ids = array_map(fn(Post $post): int => $post->id, $posts);

// to return a value by reference,
fn&($x) => $x


Enter fullscreen mode Exit fullscreen mode

They only allow one expression; that one expression can be spread over multiple lines for formatting.

Another significant difference between short and normal closures is that the short ones don't require the use keyword to be able to access data from the outer scope.

$modifier = 5;

array_map(fn($x) => $x * $modifier, $numbers);

// OR

$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_export($x);  // Outputs 1

Enter fullscreen mode Exit fullscreen mode

variables from the outer scope. Values are bound by value and not by reference.

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay