PHP8 已于 2020-11-26 发布,这次带来了我们期待已久的 JIT 。但这篇文章主要讲讲新特性的理解与使用。
Named arguments
我们会在函数参数列表中使用默认值:
function setUser(int $age, string $name, string $money = "0.00", int $sex = 0, $job = null)
{
}
以前当我们想要使用 $money
的默认值并设置 $sex
的值时:
setUser(12,"Lilin", "0.00", 1);
$money
的值被我们显式的设置了,似乎使函数声明中的默认值“浪费了”
在 PHP8 中,我们可以根据参数名来设置参数的值:
setUser(12,name:"Lilin", sex:1);
我们可以通过指定参数名来设置对应的参数值
这么做的好处不仅仅可以使我们更方便的使用预设的默认值。
代码不是一成不变的,在某一天我们需要维护上个月的代码,如果我遇到了这样的函数调用:
getUserWith($userId, true, 5, 100, today(), true)
我想我的内心一定是崩溃的,我可以根据经验推断出 $userId
是用户 ID , today()
是根据今天的日期搜索。但是有两个 true
, 这似乎需要阅读参数列表才能判断出来。
如果使用命名参数,情况就会变成这样:
getUserWith(userId:$userId, emailVerify:true, limit:5, offset:100, time:today(), telphoneVerify:true)
Constructor property promotion
以前我们在对象初始化时,往往这样操作:
class Point {
public float $x;
public float $y;
public float $z;
public function __construct(
float $x = 0.0,
float $y = 0.0,
float $z = 0.0
) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
现在我们可以在构造函数中完成这一切:
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
与 Named arguments 配合,我们的函数初始化将变得十分简洁:
new Point(z:1.0)