Shorten your functions! – Arrow Functions in PHP7.4

Shorten your functions! – Arrow Functions in PHP7.4

Shorthand Functions in PHP

Tired of writing anonymous functions syntax every time when you just need to pass a callback or closure? Not only the standard long syntax is confusing but it’s also hard to read and understand. Well it’s your lucky day, the short syntax is on the way to be in release code of PHP 7.4!

Generally speaking the the new form would look like:

fn(parameter_list) => expr

A sample syntax of:

function array_values_from_keys($arr, $keys) {
    return array_map(function ($x) use ($arr) { return $arr[$x]; }, $keys);

Will be replaced in PHP 7.4 by:

function array_values_from_keys($arr, $keys) {
    return array_map(fn($x) => $arr[$x], $keys);

Same as in normal closures, the $this variable, the context and the LSB scope will be automatically bind when a short closure is created inside a class method. For standard closures, this can be prevented by prefixing them with word: static.

The function signature is:

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


PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book

Rate this artcile
[Total: 1 Average: 5]

Leave a Comment