函數/方法參數支援四類類型聲明:
function foo(MyClass $obj)function bar(Iterator $it)function baz(array $arr)function qux(callable $cb)參數可預設 null:function test(MyClass $obj = null)。不支援標量類型(int/float/string/bool),PHP 7.0+ 引入標量類型聲明前,需用其他手段。
class Test {
public function testArray(array $arr) { print_r($arr); }
public function testClass(Test1 $obj = null) { print_r($obj); }
public function testCallable(callable $cb, $data) { call_user_func($cb, $data); }
public function testInterface(Traversable $it) { echo get_class($it); }
}
$t = new Test();
$t->testArray([1,2]);
$t->testClass(new Test1());
$t->testCallable('var_dump', 42);
$t->testInterface(new ArrayObject([]));
// 傳入錯誤類型拋出 TypeError (PHP 7+) / Catchable Fatal Error (PHP 5)
安裝:pecl install SPL_Types
提供五大標量包裝類:
SplInt、SplFloat、SplBool、SplStringSplEnum:枚舉類型$int = new SplInt(94);
try {
$int = 'try to cast string'; // 拋出 UnexpectedValueException
} catch (UnexpectedValueException $e) {
echo $e->getMessage(); // "Value not an integer"
}
echo $int; // 94 (自動轉字串)
| 特性 | 說明 |
|---|---|
| 類型安全 | 賦值非對應類型拋異常,運行時強制約束 |
| 自動轉換 | 支援 __toString()、數學運算等語境自動轉換 |
| 效能代價 | 物件包裝 + 運行時檢查,比原生標量慢數倍 |
| 靈活性損失 | PHP 動態特性被削弱,需權衡 |
| 擴展依賴 | 需編譯安裝 PECL 擴展,部署複雜度上升 |
原生標量類型聲明 + 嚴格模式 為首選:
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
add(1, 2); // 3
add('1', '2'); // TypeError (嚴格模式)
declare(strict_types=1)@param int $x + 靜態分析工具(Psalm/PHPStan)assert(is_int($x)) 或手動檢查類型約束是構建健壯系統的關鍵防線,隨 PHP 版本演進,原生支援已成主流,擴展方案逐步退出歷史舞台。