PHP 8 实用技巧:让你的代码更优雅高效
PHP 8 带来诸多新特性,掌握这些技巧能让代码更简洁、安全。
1. 命名参数,告别参数顺序
// 旧写法
array_fill(0, 100, 'default');
// 命名参数
array_fill(start_index: 0, count: 100, value: 'default');
函数参数多时,无需记住顺序,代码自解释。
2. 字符串包含检查
// strpos 的替代
if (str_contains($haystack, $needle)) {
// 更直观
}
// 还有 str_starts_with() 和 str_ends_with()
3. 构造器属性提升
class User {
public function __construct(
private string $name,
private int $age,
private ?string $email = null
) {
}
}
减少样板代码,属性与构造器一步定义。
4. 枚举类,告别常量类
enum Status: string {
case PENDING = 'pending';
case ACTIVE = 'active';
case BLOCKED = 'blocked';
}
// 类型安全
function updateStatus(Status $status) {
... }
5. 安全的三方比较
$result = $a <=> $b; // -1, 0, 1
排序回调中尤其好用,比手动写 if-else 清晰得多。
6. 空安全操作符
$country = $user?->getAddress()?->getCountry() ?? 'Unknown';
链式调用时任一环节为 null 就短路返回,告别冗长的 isset 判断。
这些技巧在日常开发中能显著提升代码质量。建议在项目中逐步引入,团队统一规范后维护成本会大幅降低。PHP 仍在进化,保持学习才能写出更优雅的代码。