PHP 8 新特性:让代码更优雅的四个技巧
PHP 8 带来了许多令人兴奋的特性,今天分享四个能让你的代码更简洁实用的技巧。
1. 命名参数
再也不用记住参数顺序了!
// 之前
json_encode($data, JSON_PRETTY_PRINT, 512);
// 现在
json_encode($data, flags: JSON_PRETTY_PRINT, depth: 512);
2. 构造器属性提升
简化类的定义,减少重复代码:
// 之前
class User {
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
// 现在
class User {
public function __construct(private string $name) {
}
}
3. Match 表达式
比 switch 更简洁,返回值更直观:
$status = match($code) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown'
};
4. Nullsafe 运算符
优雅处理可能为 null 的对象链:
// 之前
$country = null;
if ($user !== null && $user->getAddress() !== null) {
$country = $user->getAddress()->getCountry();
}
// 现在
$country = $user?->getAddress()?->getCountry();
这些特性不仅让代码更简洁,还能减少 bug 的发生。PHP 8 还有更多强大功能等待探索,赶快升级体验吧!