typestar

Closures and arrow functions in PHP

Two ways to close over a variable: terse fn() and explicit use().

<?php
$rate = 1.25;

// arrow functions capture enclosing variables automatically
$convert = fn(float $usd): float => round($usd * $rate, 2);
echo $convert(40.0), "\n";

// classic closures list their captures with use()
$count = 0;
$tick = function () use (&$count) {
    return ++$count;
};
$tick();
$tick();
echo $count, "\n";

How it works

  1. fn() is a one-expression arrow that captures $rate by value, automatically.
  2. A classic function () use (&$count) names its captures up front.
  3. The & makes the capture by reference, so $tick mutates the original counter.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
325
Tokens
64
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 2 of 3 in Functions, step 11 of 27 in Language basics.

← Previous Next →