PHP 8.0 引入了多项重要特性与改进,以下是关键内容解析:
1. 联合类型(Union Types)
允许变量声明多种可能的类型,语法为 TypeA|TypeB:
php
function foo(int|float $value): string|bool {
// 函数逻辑
}
- 应用场景:增强函数参数与返回值的灵活性
2. match 表达式
更简洁的模式匹配结构,替代复杂的 switch:
php
$result = match ($status) {
200 => 'Success',
404 => 'Not Found',
default => 'Unknown'
};
- 优势 :直接返回值、严格类型比较、无需
break
3. 命名参数(Named Arguments)
通过参数名传递值,避免顺序依赖:
php
function createUser(string $name, int $age = 25, string $country = 'US') {
// 逻辑
}
createUser(name: 'Alice', country: 'UK'); // 跳过 $age
- 作用:提高可读性,支持参数省略
4. 属性(Attributes)
元数据注解的官方实现:
php
#[Route('/api', methods: ['GET'])]
class ApiController {
#[Authorize(role: 'admin')]
public function delete() {}
}
- 替代方案:取代文档注释形式的注解(如 Doctrine 注释)
5. 构造器提升(Constructor Property Promotion)
简化类属性初始化:
php
class User {
public function __construct(
public string $name,
protected int $age
) {}
}
- 效果:自动声明并赋值属性,减少冗余代码
6. nullsafe 运算符(Nullsafe Operator)
链式调用中避免空值中断:
php
$country = $user?->getAddress()?->getCountry();
- 等价于 :
$user && $user->getAddress() ? $user->getAddress()->getCountry() : null
7. JIT 编译器(Just-In-Time Compilation)
提升性能(需在 php.ini 启用):
ini
opcache.jit = tracing
- 性能影响:CPU 密集型任务提升约 10%-20%
8. 错误处理改进
- 未定义变量抛出
Warning而非Notice - 算术运算符类型不匹配时抛出
TypeError
9. 字符串与数字比较优化
严格遵循数学规则:
php
0 == 'abc'; // false(8.0 前为 true)
- 原则 :数字与非数字字符串比较均返回
false
示例:联合类型 + match
php
function format(int|float $input): string {
return match (true) {
$input > 100 => "Large: $input",
$input < 0 => "Negative: $input",
default => "Value: $input"
};
}
echo format(-5.3); // 输出: Negative: -5.3
PHP 8.0 通过语法精简与类型强化,显著提升开发效率与代码健壮性。建议结合静态分析工具(如 PHPStan)充分利用新特性。