PHP 7.0 引入標量型別宣告,PHP 8.0 補全聯集型別,現代 PHP 已支援完整的型別系統:
| 類別 | 型別 | PHP 版本 | 說明 |
|---|---|---|---|
| 標量 | int | 7.0 | 整數 |
| float | 7.0 | 浮點數 | |
| bool | 7.0 | 布林值 | |
| string | 7.0 | 字串 | |
| 復合 | array | 5.1 | 陣列 |
| callable | 5.4 | 可呼叫物件 | |
| object | 7.2 | 任意物件 | |
| 類/介面 | ClassName / InterfaceName | 5.0 | 具體類或介面 |
| 特殊 | void | 7.1 | 無返回值 (僅返回型別) |
| never | 8.1 | 永不返回 (拋出例外/死循環) | |
| mixed | 8.0 | 任意型別 (等同無宣告) | |
| 聯集 | Type1|Type2 | 8.0 | 多型別任一 (如 int|string) |
| 交集 | Type1&Type2 | 8.1 | 同時滿足 (如 Countable&Iterator) |
| 可為 null | ?Type / Type|null | 7.1 / 8.0 | 允許 null 值 |
<?php
// 檔案最頂部宣告 (必須是第一行程式碼)
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
// 嚴格模式
add(1, 2); // 3 ✓
add('1', '2'); // TypeError ✗ (弱模式下會自動轉型為 3)
add(1.5, 2.5); // TypeError ✗
"123" → int)。<?php
function greet(string $name = 'Guest'): string {
return "Hello, $name";
}
function greetNullable(?string $name = null): string {
return $name ? "Hello, $name" : 'Hello, Guest';
}
function greetUnion(string|null $name = null): string { // PHP 8.0+
return $name ? "Hello, $name" : 'Hello, Guest';
}
<?php
function getUser(int $id): array|User|null { // PHP 8.0 聯集型別
if ($id < 0) return null;
if ($id === 0) return ['id' => 0, 'name' => 'Guest'];
return new User($id);
}
class User {
public function __construct(public int $id, public string $name) {}
}
若需在 PHP 5 時代或特殊場景下對標量進行強型別約束,可安裝 pecl install SPL_Types。
<?php
$int = new SplInt(94);
try {
$int = 'Try to cast a string'; // 拋出 UnexpectedValueException
} catch (UnexpectedValueException $e) {
echo $e->getMessage() . PHP_EOL; // Value not an integer
}
echo $int . PHP_EOL; // 94 (物件轉字串自動調用 __toString)
可用類別:SplInt、SplFloat、SplBool、SplString、SplEnum。
declare(strict_types=1);Type1|Type2 表達多態參數。LoggerInterface) 而非實現類。