php8常用新特性

本文介绍了PHP8中的关键新特性,包括联合类型、可空类型、数组解构的改进、命名参数、match表达式、只读属性、注解使用以及JIT带来的性能优化。这些更新旨在提高代码的清晰度和执行效率。
摘要由CSDN通过智能技术生成

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

  1. switch类似, 但判断更严格, 是===
  2. 相比switch, match会直接返回值,可以直接赋值给$result了
  3. 没有匹配会抛出异常
$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

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值