现代 PHP 在函数参数、返回值和类属性上支持类型声明 — 以及 declare(strict_types=1) 来严格执行它们。它们一起为 PHP 带来了静态类型语言的许多安全性,能够及早捕获 bug。
随处可见的类型声明
{
= ;
? = ;
{
->balance += ;
}
{
->balance;
}
}
您可以对参数、返回值和类属性进行类型声明。类型包括标量类型(int、float、string、bool)、类/接口、array、?Type(可空)和 void。
function process(int|string $id): User|null { } // union type — int OR string
function handle(Countable&Iterator $x): void { } // intersection (PHP 8.1) — BOTH
function get(): static { } // return the called class's type
function nothing(): never { } // never returns (throws/exits, PHP 8.1)
PHP 8 添加了联合类型(int|string)、交集类型和特殊返回类型(static、never)。
<?php
declare(strict_types=1); // MUST be the first statement in the file
function add(int $a, int $b): int { return $a + $b; }
add(5, 3); // ✅ 8
add("5", 3); // ❌ TypeError — strict_types REJECTS the string (no coercion)
WITHOUT strict_types (default "coercive" mode):
add("5", 3) → "5" is silently coerced to int 5 → returns 8 (lenient, can hide bugs)
WITH strict_types=1:
add("5", 3) → TypeError immediately (must pass the exact declared type)
declare(strict_types=1) 从宽松的类型强制转换切换到严格执行 — PHP 拒绝类型不匹配,而不是默默地转换它们。这可以捕获强制转换会隐藏的 bug。
类型声明和严格类型对于编写健壮、可维护的现代 PHP 至关重要,它们代表了语言从其宽松类型起源的重大演进。
在参数、返回值和属性上的类型声明使代码自我说明(签名清楚地表明预期),并让 PHP 自动捕获类型错误,而现代补充(联合类型、可空类型)使签名更加精确。
最重要的实践是 declare(strict_types=1):它将 PHP 从宽松的类型强制转换(其中 "5" 默默地变成 5,可能会隐藏 bug)切换到严格执行(以清晰的 TypeError 拒绝不匹配的类型) — 这是及早捕获 bug 并编写可靠代码的关键工具,也是推荐的现代默认做法。
理解类型声明和使用严格类型是现代 PHP 开发的专业、日常知识 — 它为 PHP 带来了静态类型语言的许多安全性,使代码更加健壮和易于维护。
由于现代 PHP 框架和精心编写的代码库广泛使用类型声明(并始终使用严格类型),掌握这一点对于编写和使用高质量的当代 PHP 至关重要,将类型安全的现代代码与容易出错的旧 PHP 宽松类型风格区分开来。