PHP 8.0重大版本更新正式发布:支持JIT编译器,性能提升高达3倍

美国时间 11 月 26 日,PHP 团队宣布 PHP 8.0 正式 GA。PHP 8.0 是 PHP 语言的最新主要版本,带来了许多新特性和优化,包括命名参数(named arguments)、联合类型(union types)、属性(attributes)、构造器属性提升(constructor property promotion)、Match 表达式、nullsafe 运算符、JIT,以及针对类型系统、错误处理和一致性的诸多改进。 #### PHP 8.0.0 下载地址 https://www.php.net/downloads #### 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, ) {} } #### 联合类型(Union Types) Union Types 支持接收多个不同类型的值,而不是单个类型。目前 PHP 已经支持两种特殊的联合类型: Type 或 null,使用特殊?Type 语法。 array 或 Traversable,使用特殊 iterable 类型。 对于类型组合,可以使用在运行时经过验证的原生联合类型声明来代替 PHPDoc 注解。 支持联合类型之后,将会允许将更多类型信息从 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'); #### Match 表达式 新的 match 很像 switch,并具有以下特性: Match 是一个表达式,表示其结果可以存储在变量中或返回。 Match 分支仅支持单行表达式,不需要 break; 语句。 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; #### PHP 8 echo match (8.0) { '8.0' => "Oh no!", 8.0 => "This is what I expected", };
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3