首页 >头条 > 正文

从未停止前进,PHP8.1带来了8个重要的新转变!

原创2021-11-11 19:17:3621849
“php是世界上最好的语言”,它从未停止前进的步伐!PHP团队目前已经发布了PHP 8.1.0 RC 5版,而下一个版本将是第六个也是最后一个候选版本 (RC 6),将于近期发布。下面就给大家介绍一下在PHP8.1中会有哪8个重要的新转变,先一睹为快吧!

1、枚举(Enums)

enum Status
{
    case draft;
    case published;
    case archived;
    
    public function color(): string
    {
        return match($this) 
        {
            Status::draft => 'grey',   
            Status::published => 'green',   
            Status::archived => 'red',   
        };
    }
}

2、只读属性(Readonly properties)

class PostData
{
    public function __construct(
        public readonly string $title,
        public readonly string $author,
        public readonly string $body,
        public readonly DateTimeImmutable $createdAt,
        public readonly PostState $state,
    ) {}
}

3、初始化程序中的新内容(New in initializers)

class PostStateMachine
{
    public function __construct(
        private State $state = new Draft(),
    ) {
    }
}

4、纤维,又名“绿线”(Fibers, a.k.a. "green threads")

$fiber = new Fiber(function (): void {
    $valueAfterResuming = Fiber::suspend('after suspending');
    
    // … 
});
 
$valueAfterSuspending = $fiber->start();
 
$fiber->resume('after resuming');

5、数组解包也支持字符串键(Array unpacking also supports string keys)

$array1 = ["a" => 1];
$array2 = ["b" => 2];
$array = ["a" => 0, ...$array1, ...$array2];
var_dump($array); // ["a" => 1, "b" => 2]

6、一种可调用类(First class callables)

function foo(int $a, int $b) { /* … */ }
$foo = foo(...);
$foo(a: 1, b: 2);

7、纯交集类型(Pure intersection types)

function generateSlug(HasTitle&HasId $post) {
    return strtolower($post->getTitle()) . $post->getId();
}

8、新array_is_list功能(The new array_is_list function)

$list = ["a", "b", "c"];
array_is_list($list); // true
$notAList = [1 => "a", 2 => "b", 3 => "c"];
array_is_list($notAList); // false
$alsoNotAList = ["a" => "a", "b" => "b", "c" => "c"];
array_is_list($alsoNotAList); // false

本文系翻译,原文地址:https://stitcher.io/blog/php-81-in-8-code-blocks

php中文网直播班

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:PHP8.1
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论条评论
    .
  • .· 2021-11-30 11:21:122楼
  • http://helper168.com/ 支持

  • **iu是**
  • **iu是**· 2021-11-30 11:19:311楼
  • http://laochuanmu.net/不错

  • 专题推荐

    推荐视频教程
  • PHP8新特性初体验(公益直播课)PHP8新特性初体验(公益直播课)
  • php8,我来也php8,我来也
  • 视频教程分类