PHP 8.x has a rich and expressive type system that catches bugs at development time and makes code self-documenting.
<?php
declare(strict_types=1); // must be first line
function add(int $a, int $b): int {
return $a + $b;
}
add(1, 2); // 3
add("1", "2"); // TypeError in strict mode!
function findUser(int $id): ?array {
return getUserFromDb($id) ?: null;
}
function normalise(int|float $n): float {
return (float) $n;
}
function process(User|Admin|null $user): void { /* */ }
function handleCollection(Countable&Iterator $c): void {
// $c must implement BOTH interfaces
}
enum Status: string {
case Active = "active";
case Inactive = "inactive";
case Pending = "pending";
public function label(): string {
return match($this) {
Status::Active => "Active User",
Status::Inactive => "Inactive User",
Status::Pending => "Pending Approval",
};
}
}
$s = Status::Active;
echo $s->value; // active
echo $s->label(); // Active User
function abort(int $code, string $message): never {
http_response_code($code);
echo json_encode(["error" => $message]);
exit;
}