编程

PHP 8.1 发布了

Martin Hwang 957 2021-12-05 19:49:39

PHP 团队宣布了 PHP 8.1 发布的消息 :

? PHP 8.1 is released!

? Read all about it at: https://t.co/ToeHc3YGau

♻️ Migration Guide: https://t.co/BVVZ7lSXd1

? Many thanks to the contributors for everything they implemented, and the RMs to get this amazing new version released!

❓ What's your favourite new feature?

— php.net (@official_php) November 25, 2021

根据该消息,PHP 8.1 有以下一些新特性:

枚举

PHP 8.1 原生支持枚举(Enums), 为枚举的定义和使用提供了丰富的API:

enum Status
{
    case Draft;
    case Published;
    case Archived;
}
function acceptStatus(Status $status) {...}

只读属性

只读属性在被初始化后不能改变。你可以确保你的数据是前后一致的。PHP 8.1中,不想改变的属性可以通过定义 public 属性替代只能通过 getter 获取的私有属性 减少模板文件。

class BlogData
{
    public readonly Status $status;

    public function __construct(Status $status)
    {
        $this->status = $status;
    }
}

交叉类型(Intersection Types)

当需要同时满足多重约束时,你可以使用交叉类型

function count_and_iterate(Iterator&Countable $value) {
    foreach ($value as $val) {
        echo $val;
    }

   count($value);
}

First-class Callable 语法 

你可以使用可调用类型(callable),并传入 … 生成闭包:

function add(int $a, int $b) {
    // ...
}

$add = add(...);
$add(1, 5);
$add(5, 3);

更多…

 

获取新特性的更多信息,请到 PHP 8.1 的发布页面查看。