自 PHP 5 起引入型別提示,允許在函數簽名中指定參數預期型別,若實際傳入型別不符將拋出可捕獲的致命錯誤(Catchable fatal error),有助於提前發現錯誤、增強程式碼可讀性與 IDE 自動完成能力。
PHP 5/7 僅支援兩類型別提示:
標量型別(int、string、float、bool)在 PHP 5 中不支援,PHP 7 才正式引入標量型別宣告與嚴格模式。
function demo(array $options) {
var_dump($options);
}
// 正確呼叫
demo(['key' => 'value']);
// 錯誤呼叫:傳入字串而非陣列
$options = 'options';
demo($options);
// Catchable fatal error: Argument 1 passed to demo() must be of the type array, string given
function setLogger(?Logger $logger = null) { // PHP 7.1+ 可用 ?Logger
// ...
}
function demo(string $str) { } // PHP 5 視 string 為類別名
$str = "hello";
demo($str);
// Catchable fatal error: Argument 1 passed to demo() must be an instance of string, string given
| 優點 | 缺點 |
|---|---|
| 提早攔截型別錯誤 | 增加程式碼冗長度 |
| 提升可讀性、文件化效果 | 違背 PHP 弱型別靈活本質 |
| IDE 智慧提示更精準 | PHP 5 無標量型別支援 |
| 捕獲特定異常類別更方便 | 過度使用導致耦合度上升 |
型別提示是 PHP 邁向強型別語言特性的重要一步。PHP 7+ 已完整支援標量與回傳型別宣告,建議新專案積極採用,並搭配 declare(strict_types=1) 嚴格模式,打造更健壯的應用程式。