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
fn()is a one-expression arrow that captures$rateby value, automatically.- A classic
function () use (&$count)names its captures up front. - The
&makes the capture by reference, so$tickmutates the original counter.
Keywords and builtins used here
echofunctionreturnrounduse
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.
Step 2 of 3 in Functions, step 11 of 27 in Language basics.