PHP8 已經(jīng)發(fā)布,來(lái)看看有哪些新特性吧

PHP8 在經(jīng)過(guò)6個(gè)月的核心開發(fā)和內(nèi)測(cè)后今天終于發(fā)布了第一個(gè) GA 版本。關(guān)于 PHP8新特性的文章各位讀者可能也有閱讀過(guò),今天小編會(huì)講解PHP8里幾個(gè)核心的特性。

一
注解
現(xiàn)在在PHP8中你可以使用[#[]]標(biāo)簽來(lái)給類進(jìn)行注解。
#[Attribute]
class ListensTo
{
public string $event;
public function __construct(string $event)
{
$this->event = $event;
}
}通過(guò)注解你可以將:匿名類、函數(shù)、常量、閉包函數(shù)添加類屬性中。
#[
Route(Http::POST, '/products/create'),
Autowire,
]
class ProductsCreateController
{
public function __invoke() { /* … */ }
}你可以使用反射來(lái)獲取它們,你可以向[getAttributes]傳遞可選的參數(shù),以便過(guò)濾結(jié)果。
$attributes = $reflectionClass->getAttributes(
ContainerAttribute::class,
ReflectionAttribute::IS_INSTANCEOF
);
二
語(yǔ)法糖
?????在 PHP8 中新增了幾個(gè)語(yǔ)法糖,可以了解一下。
1丶Class Names(類名)
從 PHP8 開始,你也可以在對(duì)象上使用 [::class]:
Order::class;
$object::class;2丶Numeric Values(數(shù)值)
使用[_]操作符來(lái)格式化數(shù)字值:
$price = 100_10;
// $100 and 10 cents3丶Trailing Commas(逗號(hào))
在以下地方允許使用逗號(hào):
數(shù)組(Arrays)
方法調(diào)用(Function calls)
方法定義(Function definitions)
閉包方法 use(Closure use statements)

三
異常
? ? ?拋出異常現(xiàn)在是一個(gè)表達(dá)式,這意味著你有更多的地方可以拋出,比如短閉包或作為閉包方法回調(diào)時(shí)。
$error = fn($message) => throw new Error($message);
$input = $data['input'] ?? throw new Exception('Input not set');你也不必再用[try catch]捕捉異常了。
try {
// …
} catch (SpecificException) {
throw new OtherException();
}
四
匹配
類似于[switch],但有很強(qiáng)的類型檢查,沒(méi)有[break]關(guān)鍵字,匹配對(duì)應(yīng)的關(guān)鍵字然后返回一個(gè)值。這個(gè)可以看鳥哥的博客,有很詳細(xì)的講解。
$message = match ($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'unknown status code',
};
五
已命名參數(shù)
? ? ?用參數(shù)名傳遞參數(shù)而不是參數(shù)的順序。
setcookie(
name: 'test',
expires: time() + 60 * 60 * 2,
);已命名的參數(shù)也支持[...]傳參。
$data = [
'name' => 'test',
'expires' => time() + 60 * 60 * 2,
];
setcookie(...$data);

關(guān)于PHP8的新特性還有很多,本文就講解了幾個(gè)大家會(huì)常用到的,[JIT] 和 [Preloading] 也是PHP8中值得關(guān)注的新特性,由于篇幅有限就不一一贅述了。

如果覺(jué)得文章不錯(cuò)歡迎點(diǎn)贊和轉(zhuǎn)發(fā),關(guān)注本公眾號(hào)不定期推送PHP技術(shù)文章。

