宁泽林_NiZerin - 互联网技术博客

  • PHP
  • Go
  • Java
  • Rust
  • Python
  • 交流群
  • 关于我
  • 留言版
  1. 首页
  2. PHP
  3. 正文

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

2020年12月17日 923点热度 2人点赞 3条评论
PHP8 在经过6个月的核心开发和内测后今天终于发布了第一个 GA 版本。关于 PHP8新特性的文章各位读者可能也有阅读过,今天小编会讲解PHP8里几个核心的特性。
一
注解
现在在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
);
二
语法糖
     
在 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)

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

$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],但有很强的类型检查,没有[break]关键字,匹配对应的关键字然后返回一个值。这个可以看鸟哥的博客,有很详细的讲解。

$message = match ($statusCode) {
    200, 300 => null,
    400 => 'not found',
    500 => 'server error',
    default => 'unknown status code',
};
五
已命名参数
     
用参数名传递参数而不是参数的顺序。

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

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

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

setcookie(...$data);
关于PHP8的新特性还有很多,本文就讲解了几个大家会常用到的,[JIT] 和 [Preloading] 也是PHP8中值得关注的新特性,由于篇幅有限就不一一赘述了。
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: php
最后更新:2020年12月17日

NiZerin

博主已经躺平了,后面很少会更新博客。

打赏 点赞
< 上一篇
下一篇 >

文章评论

  • 电影里的路人

    ---

    2021年1月11日
    回复
    • 庞.统

      @电影里的路人 。。

      2021年1月31日
      回复
      • Marhoo🐝

        @庞.统 哈哈哈哈哈

        2021年6月12日
        回复
  • razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
    取消回复

    分类
    • Angular
    • CSS3
    • docker
    • Flutter
    • git
    • Go
    • H5
    • Java
    • JavaScript
    • Laravel
    • linux
    • Node.js
    • PHP
    • Python
    • React
    • redis
    • Vue.js
    • windows
    • WordPress
    • 交流
    • 小程序
    • 工具
    • 网站公告
    标签聚合
    javascript go php flutter vue translations laravel wordpress
    友情链接
    • PHP函数字典
    • 宝塔运维特惠
    • 科学上网
    • 阿里云特惠

    COPYRIGHT © 2021 nizer.in. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang