Modern PHP: match, Arrow Functions and Strict Typing
Three features of PHP 8 that make code shorter and safer
🔀 1. Expression match()
Result:
Try a grade
function calificar(float $nota): string {
return match(true) {
$nota >= 9 => 'Sobresaliente',
$nota >= 7 => 'Notable',
$nota >= 5 => 'Bien',
$nota >= 4 => 'Suficiente',
default => 'Insuficiente',
};
}
💡 match vs switch
match compares with === (no type conversion), doesn't need break, and it's an expression: it returns a value directly. With match(true) you can evaluate conditions instead of just exact values.
➡️ 2. Arrow Functions (fn)
Prices with IVA (21%):
Enter several prices
$precios = [10, 25.5, 99.9];
$preciosConIva = array_map(fn($p) => round($p * 1.21, 2), $precios);
💡 fn vs function()
fn($p) => round($p * 1.21, 2) is equivalent to function($p) use ($iva) { return round($p * $iva, 2); }, but it automatically captures variables from the surrounding scope (here it doesn't even need use) and it's a single expression.
🧩 3. Tipado Estricto (declare(strict_types=1))
Result of sumarEstricta():
Try the typed function
declare(strict_types=1);
function sumarEstricta(int $a, int $b): int {
return $a + $b;
}
sumarEstricta(5, 3); // 8, correctosumarEstricta(5.5, 3); // TypeError: 5.5 no es un int exacto
💡 ¿Por qué activar strict_types?
Without declare(strict_types=1), PHP automatically converts types ("5.5" would get truncated to 5). With strict typing, a value that doesn't exactly match the declared type throws a TypeError, helping you catch bugs earlier.
🎯 Key Concepts
match()
- Strict comparison (
===) - It's an expression, it returns a value
Arrow functions
- Short syntax:
fn($x) => ... - Automatically capture external variables
strict_types
- Declared at the top of the file
- Prevents silent type conversions
💪 Practical Exercise
Practice what you've learned
- Rewrite
calificar()using amatchwith ranges defined as constants. - Use
array_filterwith an arrow function to keep only the prices greater than 20€. - Create a function
restarEstricta(int $a, int $b): intand test what happens if you pass it an array.
Solution 2
$carosSolo = array_filter($precios, fn($p) => $p > 20);
Solution 3
function restarEstricta(int $a, int $b): int {
return $a - $b;
}
restarEstricta([1,2], 3); // TypeError: Argument #1 ($a) must be of type int, array given