BeginnerLesson 5 of 16
Functions with Types & Named Arguments – PHP
Parameters, return types, default values, variadics and arrow functions.
You define functions with function. In modern PHP you add types for parameters and the return value. With named arguments (PHP 8) you pass values by name – in any order and skipping default values.
<?php
function begruesse(string $name, string $gruss = "Hello"): string {
return "$gruss, $name!";
}
echo begruesse("Ada"), "\n";
echo begruesse(gruss: "Hi", name: "Linus"), "\n";With ... you accept any number of arguments (variadic) or unpack an array into arguments (spread). Arrow functions (fn) are short closures for a single expression.
<?php
function summe(int ...$zahlen): int {
return array_sum($zahlen);
}
echo summe(1, 2, 3, 4), "\n"; // 10
$werte = [5, 6];
echo summe(...$werte), "\n"; // 11
$quadrat = fn(int $x): int => $x * $x;
echo implode(",", array_map($quadrat, [1, 2, 3])), "\n"; // 1,4,9Types can be nullable (?float) or a union (int|string). void means: no return value.
<?php
function teile(float $a, float $b): ?float {
return $b == 0 ? null : $a / $b;
}
var_dump(teile(1, 0)); // NULL
var_dump(teile(6, 3)); // float(2)
function zeige(int|string $wert): void {
echo "Value: $wert\n";
}
zeige(5);
zeige("five");WarningFunctions have their own scope: variables from outside are not visible inside. Pass them as parameters. Arrow functions capture outer variables automatically (by value); normal closures need
use ($var).TipPut
declare(strict_types=1); at the top of the file. Then PHP no longer silently converts "5" to int but throws a TypeError – this catches many errors early.