PHP 8.0 已发布,有哪些最新特性?

PHP 8.0 是 PHP 语言的一个主版本更新。
它包含了很多新功能与优化项, 包括命名参数、联合类型、注解、构造器属性提升、match 表达式、nullsafe 运算符、JIT,并改进了类型系统、错误处理、语法一致性。

  • 命名参数
#PHP7
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
#PHP8
htmlspecialchars($string, double_encode: false);

这个语法就像python,指定参数名即可 double_encode: false ,直接跳过$flags , $encoding参数,设置$double_encode

PHP 8.0 已发布,有哪些最新特性?
  • 注解
#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 声明来解析

#[ReadOnly]
#[Property(type: 'function', name: 'Hello')]
function Hello()
{
    return "Hello";
}

#使用反射API读取属性
$reflection = new ReflectionFunction("Hello");
$attributes = $reflection->getAttributes();
$result = [];
foreach ($attributes as $attribute)
{
     $result[$attribute->getName()] = $attribute->getArguments();
}
print_r($result);

#-----------------------------
# OUTPUT
#-----------------------------
Array
(
    [ReadOnly] => Array
        (
        )

    [Property] => Array
        (
            [type] => function
            [name] => Hello
        )

)

关于注解:https://www.php.net/manual/zh/language.attributes.overview.php

构造器属性提升

构造器的参数直接提升为属性,更少的代码来定义并初始化属性

#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一直是弱类型语言,增加这个可以在运行时自动判断

#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
  • 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;

这个特性非常有用,让代码更美观,而不需要条件检查 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 级异常。

新增了几个比较实用的函数

# str_contains()、 str_starts_with()、 str_ends_with()

str_starts_with ( string $haystack , string $needle ) : bool
str_ends_with ( string $haystack , string $needle ) : bool

$str = "beginningMiddleEnd";
if (str_starts_with($str, "beg")) echo "printed\n";
if (str_starts_with($str, "Beg")) echo "not printed\n";
if (str_ends_with($str, "End")) echo "printed\n";
if (str_ends_with($str, "end")) echo "not printed\n";
 
// empty strings:
if (str_starts_with("a", "")) echo "printed\n";
if (str_starts_with("", "")) echo "printed\n";
if (str_starts_with("", "a")) echo "not printed\n";
if (str_ends_with("a", "")) echo "printed\n";
if (str_ends_with("", "")) echo "printed\n";
if (str_ends_with("", "a")) echo "not printed\n";

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

  • 算术/位运算符更严格的类型检测 RFC
  • Abstract trait 方法的验证 RFC
  • 确保魔术方法签名正确 RFC
  • PHP 引擎 warning 警告的重新分类 RFC
  • 不兼容的方法签名导致 Fatal 错误 RFC
  • 操作符 @ 不再抑制 fatal 错误。
  • 私有方法继承 RFC
  • Mixed 类型 RFC
  • Static 返回类型 RFC
  • 内部函数的类型 Email thread
  • 扩展 Curl、 Gd、 Sockets、 OpenSSL、 XMLWriter、 XML 以 Opaque 对象替换 resource。

其他语法调整和改进

  • 允许参数列表中的末尾逗号 RFC、 闭包 use 列表中的末尾逗号 RFC
  • 无变量捕获的 catch RFC
  • 变量语法的调整 RFC
  • Namespace 名称作为单个 token RFC
  • 现在 throw 是一个表达式 RFC
  • 允许对象的 ::class RFC

新的类、接口、函数

版权声明:本文为NII.CN的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://nii.cn/4109.html 发布者:nii

(1)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
nii的头像nii
上一篇 2022-08-07 10:25
下一篇 2022-08-09

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

联系我们

邮件:83390286[AT]QQ.COM

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信