PHP Tipe Data Skalar Compound Type Declarations Strict
Definisi
PHP punya tipe skalar (int, float, string, bool), compound (array, object), dan khusus (null, resource). Sejak PHP 7+ kita bisa menulis type declarations pada argumen/return (function x(int $a): string), dan declare(strict_types=1) memaksa ketat tanpa coercition.
Kapan dipakai
Selalu deklarasikan tipe untuk API/library agar bug tipe ketahuan di awal. Untuk script cepat bisa lewat, tapi production sebaiknya strict.
Cara kerja
declare(strict_types=1);
function total(int $a, int $b): int {
return $a + $b;
}
$arr = [1, 2, "3"]; // array compound
$obj = new stdClass(); // object
$n = null; // nullStruktur alur
Loading diagram...
Catatan implementasi
strict_typeshanya berlaku per file (di baris pertama).mixed(PHP 8) menerima apa saja; hindari kalau bisa.?typeuntuk nullable (?string).- Coercion terjadi bila strict mati (string "3" → int 3).
Kesalahan umum
- Lupa strict_types: coercition diam-diam (bug halus).
- Null tanpa ?:
TypeErrorbila null lewat. - mixed berlebihan: kehilangan keamanan tipe.
- Banding
==vs===:==abaikan tipe; pakai===.