PHP Type System

PHP Type System

PHP 8.x has a rich and expressive type system that catches bugs at development time and makes code self-documenting.

1 - Strict Types

<?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!

2 - Nullable

function findUser(int $id): ?array {
    return getUserFromDb($id) ?: null;
}

3 - Union Types (PHP 8)

function normalise(int|float $n): float {
    return (float) $n;
}

function process(User|Admin|null $user): void { /* */ }

4 - Intersection Types (PHP 8.1)

function handleCollection(Countable&Iterator $c): void {
    // $c must implement BOTH interfaces
}

5 - Enums (PHP 8.1)

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

6 - never Return Type

function abort(int $code, string $message): never {
    http_response_code($code);
    echo json_encode(["error" => $message]);
    exit;
}

Note: Add declare(strict_types=1) to every PHP file. It costs nothing at runtime and eliminates an entire class of silent type coercion bugs that are notoriously difficult to track down.

-Tip-