编程

PHP 8.0 新特性 [命名参数,构造器属性提升,match 语法,nullsafe 操作符, 字符串数字比较,等等]

946 2021-12-29 00:17:51

命名参数 

PHP 7

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

PHP 8

htmlspecialchars($string, double_encode: false);

  • 只需要指定必填参数,跳过可选参数。
  • 参数的顺序无关、自己就是文档(self-documented)

注解 

//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 原生语法来使用结构化的元数据,代替 PHPDoc 的注解方式。

构造器属性提升 

//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,
  ) {}
}

现在可以使用更少的样板代码来定义并初始化属性。

联合类型

//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 表达式 

//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 运算符 

//PHP 7
$country =  null;
if ($session !== null) {
  $user = $session->user;
  if ($user !== null) {
    $address = $user->getAddress();
 
    if ($address !== null) {
      $country = $address->country;
    }
  }
}
//PHP 8
$country = $session?->user?->getAddress()?->country;

现在可以用新的 nullsafe 运算符链式调用,而不需要使用 null 条件检查。 如果链条中的一个元素失败了,则整个链条会中止并赋值为 Null。

字符串与数字的比较更符合逻辑 

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

PHP 8 比较数字字符串(numeric string)时,会按数字进行比较。 不是数字字符串时,将数字转化为字符串,按字符串比较。

内部函数类型错误的一致性

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

PHP