The earlier Functions lesson covered named functions and arrow functions. This one covers functions used as values — passed around, stored in variables, and passed into other functions.
A function with no name, assigned directly to a variable or passed inline.
$greet = function ($name) {
return "Hello, $name!";
};
echo $greet('Sam'); // Hello, Sam!An anonymous function normally can't see variables from outside its own body — use explicitly imports one.
$taxRate = 0.08;
$addTax = function ($price) use ($taxRate) {
return $price * (1 + $taxRate);
};
echo $addTax(100); // 108Several built-in PHP functions accept a function as an argument, to run once per item.
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(function ($n) {
return $n * 2;
}, $numbers);
// [2, 4, 6, 8, 10]
$evens = array_filter($numbers, function ($n) {
return $n % 2 === 0;
});
// [2, 4]Arrow functions as a shortcut
The arrow functions from the earlier Functions lesson (fn($n) => $n * 2) work as callbacks too, and automatically capture outside variables without needing use — often the shorter choice for a simple one-line callback.
function factorial(int $n): int {
if ($n <= 1) {
return 1;
}
return $n * factorial($n - 1);
}
echo factorial(5); // 120Always have a base case
Every recursive function needs a base case — a condition that stops it calling itself. Without one, it recurses until PHP runs out of memory.
A parameter prefixed with ... collects every remaining argument into an array.
function sum(...$numbers): int {
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
echo sum(1, 2, 3, 4, 5); // 15Arguments can be passed by parameter name instead of position — useful for a function with several optional parameters, so it's clear at the call site what each value means.
function makeUser(string $name, string $role = 'user', bool $active = true) {
// ...
}
makeUser(name: 'Sam', active: false);
// role keeps its default value, active is explicitly set — order doesn't matter