Functions
Typed parameters and return types, defaults, named arguments, arrow functions and closures.
Runs in Zerethon IDE · PHP 8.4
Official PHP documentation ↗
main.php
<?php
declare(strict_types=1);
function greet(string $name, string $greeting = 'Hello'): string
{
return "$greeting, $name!";
}
function stats(int ...$numbers): array
{
return [min($numbers), max($numbers), array_sum($numbers) / count($numbers)];
}
echo greet('Ada'), ' ', greet(greeting: 'Hi', name: 'Linus'), "\n";
[$low, $high, $mean] = stats(4, 8, 6);
echo "$low $high $mean\n";
$factor = 3;
$times = fn (int $x): int => $x * $factor; // captures $factor automatically
$add = function (int $x) use ($factor): int { // a closure lists what it uses
return $x + $factor;
};
echo $times(5), ' ', $add(5), "\n";
Output
Hello, Ada! Hi, Linus! 4 8 6 15 8
- Functions do not see outside variables: pass them as parameters, or
use ($x)in a closure. - Arrow functions (
fn) are one expression and capture outside variables by value. - Types are checked when the function is called; with
strict_types=1,greet(5)is aTypeErrorinstead of a conversion.