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
