php · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The price changes after the closure is made. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$price = 10;
$show = function () use ($price) {
return "Price: $price";
};
$price = 99;
echo $show() . "\n";
$quick = fn() => "Quick: $price";
echo $quick() . "\n";
your turn
Your turn. Build a label maker.
makeLabel hands back a closure that remembers the shop. Type a shop name in the first blank and two items in the others.
fix it
The sale closure cannot see the discount. Fix it.
- The error is
Undefined variable $discounton line 4, but line 2 sets it. Why can the closure not see it? - A full
functionclosure sees only its parameters and the values listed afteruse. - On line 3, add
use ($discount)between(int $price)and: int, then run it.
nailed it
your functions travel as values now. :D
- A closure is a nameless function stored in a variable.
usecopies outside values in at the moment the closure is made.- Type a parameter
callableto accept any function value.
new words in your collection
- closure
- callable
- first-class callable
This lesson isn’t saved. A free account remembers every lesson you finish.