PHP技巧:让代码更简洁高效的5个小贴士
现代 PHP(8.x)带来了许多新特性,能让代码更简洁、安全。下面分享 5 个实用技巧,提升日常开发效率。
1. 构造器属性提升
再也不用手动声明属性并赋值了:
// 传统写法
class User {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
// 属性提升
class User {
public function __construct(public string $name) {
}
}
2. match 表达式
比 switch 更简洁,且是表达式,可直接返回:
$status = match ($code) {
200, 201 => 'success',
404 => 'not found',
default => 'unknown',
};
3. 数组解包与展开
用 ... 轻松合并数组,替代 array_merge:
$first = ['a', 'b'];
$second = ['c', 'd'];
$merged = [...$first, ...$second]; // ['a', 'b', 'c', 'd']
4. 命名参数
当函数参数很多时,命名参数让调用更清晰:
function sendEmail(string $to, string $subject = '', bool $urgent = false) {
... }
sendEmail(
to: 'user@example.com',
urgent: true
);
5. 更友好的字符串函数
PHP 8 新增了 str_contains、str_starts_with 等,告别 strpos 的晦涩:
if (str_starts_with($url, 'https')) {
// 安全连接
}
这些特性不仅减少代码量,也让意图更明确。善用它们,写出更优雅的 PHP 代码吧!