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:
mixed(PHP 8.0) — boleh tipe apa saja (hindari kecuali perlu)never(PHP 8.1) — fungsi yang pasti throw atau tidak pernah return (exit, die)void— fungsi tanpa returnself,static,parent— class sendiri, late static, dan parent class
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?
- Selalu tambahkan tipe — membuat IDE autocomplete & static analysis (Psalm, PHPStan) lebih kuat
- Nullable untuk "mungkin ada, mungkin tidak"
- Union untuk API fleksibel
- Strict types untuk library / kode kritis