PHP 是弱型別語言,變數型別隨賦值自動轉換,函數參數不強制檢查型別。這雖然靈活,卻極易導致執行期錯誤:
<?php
class Person {
public $name = 'CodePlayer';
public $age = 3;
}
function sayHi($person) {
echo "Hello! My name is $person->name. I'm $person->age years old.";
}
$p = '張三'; // 錯誤傳入字串
sayHi($p); // Notice: Trying to get property of non-object,但程式繼續執行
echo 'Suffix'; // 仍會輸出
?>
在函數參數前加上型別名稱,即可強制檢查,違反時拋出 Fatal Error(致命錯誤) 並終止腳本:
<?php
function sayHi(Person $person) { // 要求 Person 物件
echo "Hello! My name is $person->name. I'm $person->age years old.";
}
$person = '張三';
sayHi($person); // Fatal Error: Argument 1 must be an instance of Person
echo 'Suffix'; // 不會執行
?>
| 型別 | 支援版本 | 說明 |
|---|---|---|
| 類別名稱 | PHP 5.0+ | 需為該類別或其子類別實例 |
| 介面名稱 | PHP 5.0+ | 需實作該介面 |
array | PHP 5.1+ | 需為陣列 |
callable | PHP 5.4+ | 需為可呼叫類型(函數、閉包、陣列呼叫格式) |
不支援:標量型別(int、string、float、bool)、Traits、resource。
註:PHP 7.0+ 開始支援標量型別宣告(declare(strict_types=1)),本文聚焦 PHP 5 風格約束。
<?php
class MyClass {
// 物件型別約束
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
// 陣列型別約束
public function test_array(array $input_array) {
print_r($input_array);
}
// 介面型別約束
public function test_interface(Traversable $iterator) {
echo get_class($iterator);
}
// Callable 型別約束
public function test_callable(callable $callback, $data) {
call_user_func($callback, $data);
}
}
class OtherClass {
public $var = 'Hello World';
}
// 測試呼叫
$myclass = new MyClass;
$otherclass = new OtherClass;
// 正確
$myclass->test($otherclass); // Hello World
$myclass->test_array(['a','b','c']); // Array 輸出
$myclass->test_interface(new ArrayObject([])); // ArrayObject
$myclass->test_callable('var_dump', 1); // int(1)
// 錯誤示範(均拋出 Fatal Error)
$myclass->test('hello');
$myclass->test(new stdClass);
$myclass->test(null); // 無預設值時 null 也失敗
$myclass->test_array('a string');
?>
在型別前加 ?(PHP 7.1+)或給預設值 = null:
<?php
// PHP 5 風格:給預設值 null
function test(stdClass $obj = null) {
if ($obj === null) {
echo "無物件";
} else {
echo $obj->var;
}
}
test(null); // 正常
test(new stdClass); // 正常
?>
<?php
class MyClass { public $var = 'Hello World'; }
function MyFunction(MyClass $foo) {
echo $foo->var;
}
MyFunction(new MyClass); // 正常
?>
型別約束觸發時會自動呼叫 __autoload 或 spl_autoload_register 註冊的載入器,確保類別定義可用。
function foo(int $x),會視為類別名稱 Int。請改用 is_int() 或 PHP 7+ declare(strict_types=1)。['Class','method']、[$obj,'method']、匿名函數、函數名字串。TypeError(PHP 7+)或 Catchable Fatal Error(PHP 5),可用 try-catch 捕獲(PHP 7+)。PHP 5 型別約束雖僅限物件、介面、陣列、Callable,卻能在架構層面強制契約、提早發現錯誤、改善程式碼可讀性。配合介面導向設計、依賴注入容器,是構建健壯 PHP 應用的基石。升級至 PHP 7.4+ 後,建議全面遷移至標量型別宣告、回傳型別宣告、聯集型別等現代特性。