PHP8 已经发布,来看看有哪些新特性吧

PHP开源Hub

共 1609字,需浏览 4分钟

 · 2020-12-03

5be0560199b1930959f33a4e3e77699d.webp

PHP8 在经过6个月的核心开发和内测后今天终于发布了第一个 GA 版本。关于 PHP8新特性的文章各位读者可能也有阅读过,今天小编会讲解PHP8里几个核心的特性。

f1633bf591d5d6ff7d099c2e96f3ebb9.webp

注解


现在在PHP8中你可以使用[#[]]标签来给类进行注解。

#[Attribute]
class ListensTo
{
public string $event;

public function __construct(string $event)
{
$this->event = $event;
}
}

通过注解你可以将:匿名类、函数、常量、闭包函数添加类属性中

#[
Route(Http::POST, '/products/create'),
Autowire,
]
class ProductsCreateController
{
public function __invoke() { /* … */ }
}

你可以使用反射来获取它们,你可以向[getAttributes]传递可选的参数,以便过滤结果。

$attributes = $reflectionClass->getAttributes(
ContainerAttribute::class,
ReflectionAttribute::IS_INSTANCEOF
);
7073226e09964edefdbe846ef7de233c.webp

语法糖

     

在 PHP8 中新增了几个语法糖,可以了解一下。

1丶Class Names(类名)

从 PHP8 开始,你也可以在对象上使用 [::class]:

Order::class;

$object::class;

2丶Numeric Values(数值)

使用[_]操作符来格式化数字值:

$price = 100_10;
// $100 and 10 cents

3丶Trailing Commas(逗号)

在以下地方允许使用逗号:

数组(Arrays)

方法调用(Function calls)

方法定义(Function definitions)

闭包方法 use(Closure use statements)

7073226e09964edefdbe846ef7de233c.webp

异常

     

抛出异常现在是一个表达式,这意味着你有更多的地方可以抛出,比如短闭包或作为闭包方法回调时。

$error = fn($message) => throw new Error($message);

$input = $data['input'] ?? throw new Exception('Input not set');

你也不必再用[try catch]捕捉异常了。

try {
// …
} catch (SpecificException) {
throw new OtherException();
}
7073226e09964edefdbe846ef7de233c.webp

匹配

     

类似于[switch],但有很强的类型检查,没有[break]关键字,匹配对应的关键字然后返回一个值。这个可以看鸟哥的博客,有很详细的讲解。

$message = match ($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'unknown status code',
};
7073226e09964edefdbe846ef7de233c.webp

已命名参数

     

用参数名传递参数而不是参数的顺序。

setcookie(
name: 'test',
expires: time() + 60 * 60 * 2,
);

已命名的参数也支持[...]传参。

$data = [
'name' => 'test',
'expires' => time() + 60 * 60 * 2,
];

setcookie(...$data);
7073226e09964edefdbe846ef7de233c.webpbd17d0b3c460e11fe061eb98d93c969f.webp

关于PHP8的新特性还有很多,本文就讲解了几个大家会常用到的,[JIT] 和 [Preloading] 也是PHP8中值得关注的新特性,由于篇幅有限就不一一赘述了。

0f44a18ceb71933a37aaba99772d9ce7.webp

如果觉得文章不错欢迎点赞和转发,关注本公众号不定期推送PHP技术文章。

7073226e09964edefdbe846ef7de233c.webp
浏览 16
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报