Home » The Archive » PHP Tips: Short Arrow Functions

PHP Tips: Short Arrow Functions

Arrow Functions are a new syntax for short anonymous functions introduced in PHP 7.4.

Anonymous functions, if you're not familiar with them, are special functions written inside other sections of your code that you can pass around kind of like variables.

Usually these functions are very short and purpose-built. They're not supposed to contain a huge amount of logic.

Where arrow functions stand out is that they allow you to write concise single-operation anonymous functions like you might use when doing sorting or map/reduce operations.

=> Example Usage

Say you want to make a list of Names from your inventory of Ships:

$ships = [
    'Ship1' => ['name' => 'Rocinante'],
    'Ship2' => ['name' => 'Razorback'],

The traditional way to do this in PHP would be a foreach loop:

$names = array();

foreach ($ships as $key => $value) {
    $names[] = $value['name'];

Depending on your needs, you might choose to optimize this into an array_map, which applies a callable function to the array & returns the transformed array.

$names = array_map(
    function ($item) {
        return $item['name'];

That might not look like a huge savings, but there are some algorithms where it makes things cleaner and easier to follow.

New in PHP 7.4, this can be written like so:

$names = array_map(fn($ship) => $ship['name'], $ships);

That's a lot shorter than both earlier examples. Once we all get the hang of reading the new syntax, it'll probably feel more natural, too.

=> In Scope

One nice thing about this syntax, compared to the original anonymous function syntax, is the new way it handles Scope.

In the old way, you had to specifically include the variables you wanted to access by writing function ($param1) use ($var1, $var2) {...}.

With short function syntax, that would be too verbose, so the outer scope is automatically imported for you.

$numbers = [1, 2, 3, 4, 5];
$multipier = 10;

$product = array_map(fn($item) => $item * $multipier, $numbers);
// $product: [10, 20, 30, 40, 50];

=> Hold on there, Hoss

One important note about the "outer scope", straight from the documentation on PHP.net: Values from the outer scope cannot be modified by arrow functions. They are passed in by-value, not by-reference. Changes to them trigger an in-memory copy, rather than overwriting the outer variable. I suppose there might be some ability for objects to bypass this due to their instantiated nature.

Ultimately, what this means means is that if you were hoping to do some shenanigans like pushing values onto arrays or incrementing counters from inside your arrow function, that's a no-go for your algo.

=> What if I need more power?

Arrow functions are designed to be used in very specific use cases, where the inner logic is extremely brief. If you find that you're needing more power, you may need to look at regular Anonymous Functions, or class/object method callables, or regular non-class functions. Plenty of PHPish options in the sea, as they say.

=> What's Next

This post is the second in a series of short posts about individual PHP features that I think you might like.

Previously, I posted about the Null Coalesce operator (for a second time, actually - I forgot that I had written about it in 2018 😂).

Next up will be the Spaceship Operator introduced in PHP 7.

Published: May 3, 2020

Categories: coding

Tags: dev, development, coding, php, php-tips

Related Posts
comments powered by Disqus