Type System Lanjutan — PHP

PHP modern (8.x) punya sistem tipe yang kaya untuk membuat kode lebih aman dan jelas. Nullable types (?Type) — PHP 7.1: function cari(int $id): ?User { // Retur

PHP modern (8.x) punya sistem tipe yang kaya untuk membuat kode lebih aman dan jelas.

Nullable types (?Type) — PHP 7.1:

function cari(int $id): ?User {
    // Return User atau null jika tidak ditemukan
    return $id > 0 ? new User() : null;
}

Tanda ? di depan tipe menandakan nilai bisa tipe itu atau null.

Union types (A|B) — PHP 8.0:

function formatId(int|string $id): string {
    return "ID: $id";
}

formatId(123);     // "ID: 123"
formatId("ABC-7"); // "ID: ABC-7"

Union types memungkinkan parameter atau return menerima beberapa tipe.

Intersection types (A&B) — PHP 8.1:

function process(Countable&Iterator $data): int {
    // $data harus implement BOTH Countable dan Iterator
    return count($data);
}

Harus memenuhi semua tipe sekaligus. Berguna untuk menggabungkan interface.

Tipe khusus:

function gagal(string $pesan): never {
    throw new RuntimeException($pesan);
}

Property types (PHP 7.4+):

class Produk {
    public string $nama;
    public ?float $diskon = null;   // nullable
    public int|float $harga;        // union
    public readonly string $sku;    // readonly (PHP 8.1)
}

Strict types — declare(strict_types=1):

declare(strict_types=1);

function tambah(int $a, int $b): int {
    return $a + $b;
}

tambah(1, 2);        // OK → 3
tambah("1", 2);      // TypeError! (tanpa strict, string "1" akan di-coerce)

Deklarasi ini harus di baris pertama file. Tanpa strict, PHP melakukan type coercion otomatis (kadang berbahaya).

Kapan pakai apa?

Yang akan kamu pelajari