DEV Community

Aju Chacko
Aju Chacko

Posted on

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

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
var_export($x);  // Outputs 1

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

Top comments (0)