php8新版本中一些主要的变化是:
- 命名参数
- 属性
- 构造函数特性升级
- 联合类型
- 匹配表达式
- Nullsafe操作符
- 内部函数的一致类型错误
- 新的JIT编译引擎
下面,俺将跟大家一起来学习PHP8中的新特性:
命名参数
只指定必需的参数,跳过可选参数。
参数是顺序独立的。
// PHP 7
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
// PHP 8
htmlspecialchars($string, double_encode: false);
属性
现在可以使用带有PHP本机语法的结构化元数据,而不是使用PHPDoc注释。
// PHP 7
class PostsController
{
/**
* @Route("/api/posts/{id}", methods={"GET"})
*/
public function get($id) { /* ... */ }
}
// PHP 8
class PostsController
{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }
}
构造函数特性升级
用于定义和初始化属性的样板代码更少。
//PHP 7
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;
}
}
// PHP 8
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
联合类型
您可以使用在运行时验证的联合类型声明,而不是使用用于类型组合的PHPDoc注释。
//PHP 7
class Number {
/** @var int|float */
private $number;
/**
* @param float|int $number
*/
public function __construct($number) {
$this->number = $number;
}
}
new Number('NaN'); // Ok
//PHP 8
class Number {
public function __construct(
private int|float $number
) {}
}
new Number('NaN'); // TypeError
匹配表达式
新的match与switch类似,有以下特点:
- Match是一个表达式,这意味着它的结果可以存储在变量中或返回
- 匹配分支只支持单行表达式,不需要中断
- Match进行严格的比较
// PHP 7
switch (8.0) {
case '8.0':
$result = "Oh no!";
break;
case 8.0:
$result = "This is what I expected";
break;
}
echo $result;
//> Oh no!
// PHP 8
echo match (8.0) {
'8.0' => "Oh no!",
8.0 => "This is what I expected",
};
//> This is what I expected
Nullsafe操作符
现在,您可以使用带有新的nullsafe操作符的调用链,而不是null检查条件。当对链中的一个元素求值失败时,整个链的执行将中止,整个链的计算结果为null。
// PHP 7
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
//PHP 8
$country = $session?->user?->getAddress()?->country;
从字符串到数字比较更合理
当与数字字符串进行比较时,PHP 8使用数字比较。否则,它将数字转换为字符串并使用字符串比较。
// PHP 7
0 == 'foobar' // true
// PHP 8
0 == 'foobar' // false
这些是一些PHP8的新特性,了解所有的变化访问查看这个链接。