PHP运算符 PHP8 正式版发布了
发布时间:2022-10-24 11:31:06 所属栏目:PHP教程 来源:
导读: PHP8.0 是 PHP 的一个大版本更新。它包含许多新功能和优化,包括命名参数,联合类型,属性,构造函数属性提升,匹配表达式,nullsafe 运算符,JIT,以及类型系统的改进,错误处理和一致性。
01
01
|
PHP8.0 是 PHP 的一个大版本更新。它包含许多新功能和优化,包括命名参数,联合类型,属性,构造函数属性提升,匹配表达式,nullsafe 运算符,JIT,以及类型系统的改进,错误处理和一致性。 01 命名参数 PHP7 htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false); PHP8 htmlspecialchars($string, double_encode: false); 02 属性 PHP7 class PostsController{ /** * @Route("/api/posts/{id}", methods={"GET"}) */ public function get($id) { /* ... */ }} PHP8 class PostsController{ #[Route("/api/posts/{id}", methods: ["GET"])] public function get($id) { /* ... */ }} 现在,您可以使用具有PHP native 语法的结构化元数据来代替 PHPDoc 注释。 03 构造函数属性提升 PHP7 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; }} PHP8 class Point { public function __construct( public float $x = 0.0, public float $y = 0.0, public float $z = 0.0, ) {}} 更少的boilerplate代码来定义和初始化属性。 04 联合类型 PHP7 class Number { /** @var int|float */ private $number; /** * @param float|int $number */ public function __construct($number) { $this->number = $number; }} new Number('NaN'); // Ok PHP8 class Number { public function __construct( private int|float $number) {}} new Number('NaN'); // TypeError 可以使用在运行时验证的native联合类型声明来代替类型组合的 PHPDoc 注释。 05 匹配表达式 PHP7 switch (8.0) { case '8.0': $result = "Oh no!"; break; case 8.0: $result = "This is what I expected"; break;}echo $result;//> Oh no! PHP8 echo match (8.0) { '8.0' => "Oh no!", 8.0 => "This is what I expected",};//> This is what I expected 新的匹配表达式类似于switch,并具有以下功能: 06 nullsafe 运算符 PHP7 $country = null; if ($session !== null) { $user = $session->user; if ($user !== null) { $address = $user->getAddress(); if ($address !== null) { $country = $address->country; } }} PHP8 $country = $session?->user?->getAddress()?->country; 现在,您可以使用带有新的 nullsafe 运算符的调用链来代替空检查条件。当对链中一个元素的求值失败时,整个链的执行将中止,并且整个链的求值为空。 07 Saner 字符串与数字的比较 PHP7 0 == 'foobar' // true PHP8 0 == 'foobar' // false 与数字字符串进行比较时,PHP8 使用数字比较。否则PHP运算符,它将数字转换为字符串并使用字符串比较。 08 内部函数的一致类型错误 PHP7 strlen([]); // Warning: strlen() expects parameter 1 to be string, array given array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0 PHP8 strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0 现在,如果参数验证失败,大多数内部函数将引发 Error 异常。 09 Just-In-Time 编译 PHP8 引入了两个 JIT 编译引擎。Tracing JIT 是两者中最有希望的,它在综合基准测试中的性能提高了大约 3 倍,在某些特定的长期运行的应用程序中提高了 1.5–2 倍。典型的应用程序性能与 PHP7.4 相当。 JIT 对PHP8 性能的贡献 php高精度运算_PHP运算符_php 三目运算 10 类型系统和错误处理方面的改进 11 其他语法调整和改进 12 新的类,接口和函数 (编辑:均轻资讯网_我爱站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐


