<?php
declare(strict_types=1);
// Parameter + return types
function add(int $a, int $b): int {
return $a + $b;
}
echo "add(3, 5): " . add(3, 5) . "
";
// Nullable
function findUser(?int $id): ?string {
if ($id === null) return null;
return "User #$id";
}
echo "findUser(1): " . findUser(1) . "
";
echo "findUser(null): " . var_export(findUser(null), true) . "
";
// Union types (PHP 8)
function format(int|float $num): string {
return number_format($num, 2);
}
echo "format(42): " . format(42) . "
";
echo "format(3.14): " . format(3.14) . "
";
// Class with typed properties
class Product {
public function __construct(
public readonly string $name,
public readonly float $price,
public readonly ?string $description = null
) {}
}
$p = new Product("Widget", 29.99);
echo "Product: $p->name - \$$p->price";
?>