自 PHP 5 起,開發者可以在函數定義時使用類型提示來限制參數必須為特定類型。若呼叫端傳入的實際參數類型不符,PHP 會拋出Catchable fatal error,有效在執行期攔截型別錯誤。
PHP 僅允許兩種類型的型別聲明:
function demo(array $options) {
var_dump($options);
}
// 正確呼叫
demo(['foo' => 'bar']);
// 錯誤呼叫:傳入字串而非陣列
$options = 'options';
demo($options);
// Catchable fatal error: Argument 1 passed to demo() must be of the type array, string given
可將參數預設值設為 null,使該參數成為可選:
function demo(array $options = null) {
if ($options === null) {
$options = [];
}
var_dump($options);
}
demo(); // 不會報錯
在 PHP 5.x 中,若嘗試使用 string、int 等標量型別作為提示,PHP 會將其視為類別名稱,導致錯誤:
function demo(string $str) {}
demo("hello");
// Catchable fatal error: Argument 1 passed to demo() must be an instance of string, string given
注意:PHP 7.0 起已支援標量型別宣告(int、float、string、bool)與回傳型別宣告,詳見官方文件。
catch (SpecificException $e))。是否採用類型提示,視專案規範與團隊偏好而定。建議在核心領域模型、公開 API 介面優先使用,以增強維護性。