×

php · level 3 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a function you can keep in a variable.

Arrow functions showed you that functions can be values. A closure is the full-sized version: function with no name, as many lines as you like, stored in a variable. Call it through the variable, as in $addTax(500). To use an outside variable, list it after use, and PHP copies that value in.

A parameter typed accepts a closure, an arrow function or anything else PHP can call, and $step(...) runs whatever was handed in. Writing strtoupper(...), three dots and all, turns an existing function into a closure: a .

<?php
$tax = 20;
$addTax = function (int $pence) use ($tax): int {
    return $pence + intdiv($pence * $tax, 100);
};
function applyTwice(callable $step, int $value): int {
    return $step($step($value));
}
echo $addTax(500) . "\n";
echo applyTwice(fn(int $n) => $n * 2, 3) . "\n";
echo implode(", ", array_map(strtoupper(...), ["tea", "jam"])) . "\n";

A closure needs a ; after its closing curly bracket, because the whole thing is a value being stored.