php8常用新特性
联合类型
function processValue(int|float|string $value): void {
#some code
}
可空类型
function processValue(?string $value): void {
#some code
}
数组解构
php8之前我们使用list
$array = ['Apple', 'Banana', 'Cherry'];
list($fruit1, $fruit2, $fruit3) = $array;
echo $fruit1; // Output: Apple
echo $fruit2; // Output: Banana
echo $fruit3; // Output: Cherry
php8可以这么写
$array = ['Apple', 'Banana', 'Cherry'];
[$fruit1, $fruit2, $fruit3] = $array;
//支持空槽
[, $fruit4, $fruit5] = $array;
//支持指定键名为变量名
$array = ['name' => 'John', 'age' => 30, 'city' => 'New York'];
['name' => $name, 'age' => $age, 'city' => $city] = $array;
命名参数
// before
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, ini_get('default_charset'), false);
// 可以指定传入第四个参数,而不用和之前一样按顺序写满参数
htmlspecialchars($string, double_encode: false);
匹配表达式match
- 和
switch
类似, 但判断更严格, 是===
- 相比switch, match会直接返回值,可以直接赋值给$result了
- 没有匹配会抛出异常
$value = 2;
$result = match ($value) {
1 => 'One',
2 => 'Two',
3, 4 => 'Three or Four',
default => 'Other'
};
只读 readonly
类
// PHP 8.2
readonly class User {
public string $username;
public int $uid;
}
// PHP 8.1 等效写法
class User {
public readonly string $username;
public readonly int $uid;
}
注解Attributes
以前的注解写法, 通过反射去获取注释并解析字符串, 提取对应信息.
/**
* @param Foo $argument
* @see https:/xxxxxxxx/xxxx/xxx.html
*/
function dummy($Foo) {}
php8写法
#[Params("Foo", "argument")]
#[See("https://xxxxxxxx/xxxx/xxx.html")]
function dummy($argument) {}
//也可以写成
#[
Params("Foo", "argument"),
See("https://xxxxxxxx/xxxx/xxx.html")
]
function dummy($argument) {}
//通过反射来获取注解
$ref = new ReflectionFunction("dummy");
var_dump($ref->getAttributes("See")[0]->getName());
var_dump($ref->getAttributes("See")[0]->getArguments());
JIT带来的性能优化
- Opcache会做opcode层面的优化
- PHP8的JIT目前是在Opcache之中提供的
- JIT在Opcache优化之后的基础上,结合Runtime的信息再次优化,直接生成机器码
- JIT不是原来Opcache优化的替代,是增强
- 目前PHP8只支持x86架构的CPU
参考文章:
https://juejin.cn/post/7174952438146236476
https://juejin.cn/post/7243748398567391288
https://twosee.cn/2020/07/17/php8-rfc-named-params/
https://www.laruence.com/2020/06/12/5902.html
https://www.laruence.com/2020/07/13/6033.html
https://www.laruence.com/2020/06/27/5963.html