首頁  >  文章  >  從未停止前進,PHP8.1帶來了8個重要的新轉變!

從未停止前進,PHP8.1帶來了8個重要的新轉變!

藏色散人
藏色散人原創
2021-11-10 16:21:014498瀏覽

“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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn