PHP8 新特性

2021年1月2日 185点热度 0人点赞 0条评论

命名参数属性构造函数属性提升联合类型Match 表达式Nullsafe 操作符更合理的字符串与数值的比较内置函数的一致错误类型JIT 编译类型系统和错误处理的改进其他的语法微调和改进新类、接口、和函数

PHP 8.0.0 Released!

26 Nov 2020 PHP 开发组宣布 PHP 8.0.0 可用。

PHP 8.0 是 PHP 语言的主要更新。它包含了许多新特性和优化,包括命名参数、联合类型、属性、构造函数属性提升、匹配表达式、nullsafe 操作符、JIT,以及对类型系统、错误处理和一致性的改进。

命名参数

Named arguments

PHP 7

htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8'false);

PHP 8

htmlspecialchars($string, double_encode: false);
  • 只指定必需参数,跳过可选参数。

  • 参数是独立于顺序并且是自描述的。

属性

Attributes

属性,在很多语言中亦称作注解。

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) /* ... */ }
}

不再使用 PHPDoc 注释,现在可以使用 PHP 原生语法的结构化元数据。

构造函数属性提升

Constructor property promotion

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

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

可使用联合类型声明在运行时验证类型来代替使用 PHPDoc 注释说明。

Match 表达式

Match expression

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

match 类似于 switch,具有如下特性:

  • match 为表达式,意味着其结果可以存储在变量中或用于返回。

  • match 分支仅支持单行表达式,同时不需要 break; 语句。

  • match 使用严格比较。

Nullsafe 操作符

Nullsafe operator

PHP 7

// PHP 7
$country =  null;

if ($session !== null) {
  $user = $session->user;

  if ($user !== null) {
    $address = $user->getAddress();

    if ($address !== null) {
      $country = $address->country;
    }
  }
}

PHP 8

// PHP 8
$country = $session?->user?->getAddress()?->country;

可使用 nullsafe 操作符完成链式调用来代替 null 的验证。当对链中的一个元素求值失败时,整个链的执行将中止,整个链的求值为 null。

更合理的字符串与数值的比较

Saner string to number comparisons

PHP 7

// PHP 7
0 == 'foobar' // true

PHP 8

// PHP 8
0 == 'foobar' // false

当数值与数值字符串比较时,PHP 8 使用数值比较。否则将数值转换为字符串并采用字符串比较。

内置函数的一致错误类型

Consistent type errors for internal functions

PHP 7

// PHP 7
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

PHP 8

// PHP 8
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 异常。

JIT 编译

Just-In-Time compilation

PHP 8 引入了两个 JIT 编译引擎。Tracing JIT 是其中最有前景的,它在合成基准测试上的性能提高了3倍,在一些特定的长时间运行的应用程序上的性能提高了1.5-2倍。典型的应用程序性能与 PHP 7.4 相当。

图片

图像来自,https://www.php.net/images/php8/scheme.svg)

类型系统和错误处理的改进

Type system and error handling improvements

  • 算术/位操作中更严格的类型检查 RFC

  • 抽象 trait 方法验证 RFC

  • 魔术方法的正确签名 RFC

  • 重分类的引擎警告 RFC

  • 不兼容方法签名的致命错误 RFC

  • @ 操作符不在静默致命错误。

  • 私有方法的继承 RFC

  • 混合类型 RFC

  • 静态返回类型 RFC

  • 内部函数 email_thread 的类型

  • 用于代替 Curl, Gd, Sockets, OpenSSL, XMLWriter 和 XML 扩展资源的封装对象

其他的语法微调和改进

Other syntax tweaks and improvements

  • 允许在参数列表 RFC 和闭包 use 列表 RFC 后尾随逗号

  • 未使用的捕获 RFC

  • 变量语法微调 RFC

  • 命名空间名称视为一个 token RFC

  • Throw 调整为表达式 RFC

  • 允许对象上使用 ::class 语法  RFC

新类、接口、和函数

New Classes, Interfaces, and Functions·

  • Weak Map 类

  • Stringable 接口

  • str_contains(), str_starts_with(), str_ends_with()

  • fdiv()

  • get_debug_type()

  • get_resource_id()

  • token_get_all() 对象实现

  • New DOM Traversal and Manipulation APIs

篇外

从 PHP 4,PHP 5,PHP 7 到今天看到 PHP 8 发布,白驹过隙呀!

6940PHP8 新特性

root

这个人很懒,什么都没留下

文章评论