酆叔のBlog

  • 首页
  • 分享技术
  • 八卦黑料
  • 生活日常
  • 日记
酆叔のBlog
上辈子作恶多端,这辈子早起上班。
  1. 首页
  2. IT技术
  3. 正文

PHP8特性

2023年10月16日 868点热度 0人点赞 0条评论

1.命名参数

命名参数可以让函数或者方法的调用更加清晰直观

function foo(string $a, string $b, ?string $c = null, ?string $d = null) { }

2.联合类型

相对于以前的 PHPDoc 声明类型的组合, 现在可以用原生支持的联合类型声明取而代之,可在实际运行中验证。

// PHP7
class Number {
  /** @var int|float */
  private $number;
  /**
   * @param float|int $number
   */
  public function __construct($number) {
    $this->number = $number;
  }
}
new Number('NaN'); // Ok
// PHP8
class Number {
  public function __construct(
    private int|float $number
  ) {}
}
new Number('NaN'); // TypeError

3.新的 mixed类型

可在某些情况下代替switch。 mixed也可以用作参数或属性类型,而不仅仅是返回类型。 由于mixed已经包含null,因此不允许将其设置为nullable。

4.最具贡献的特性:JIT

JIT作为PHP底层编译引擎,对于PHP8的性能贡献是非常之大,不过对于常规WEB应用来说,优势不明显,但仍然是非常的高大上特性,是PHP8的扛鼎之作。 PHP 8 引入了两个即时编译引擎。Tracing JIT 在两个中更有潜力,它在综合基准测试中显示了三倍的性能, 并在某些长时间运行的程序中显示了 1.5-2 倍的性能改进。典型的应用性能则和 PHP 7.4 不相上下。 最实用的特性:构造器属性提升、Nullsafe运算符、str_contains()、 str_starts_with()、 str_ends_with()

5.构造器属性提升

这个新的语法糖来用来创建值对象或数据传输对象。不用为类属性和构造函数指定它们,PHP 现在可以将它们合并为一个。


class Money 
{
    public Currency $currency;
 
    public int $amount;
 
    public function __construct(
        Currency $currency,
        int $amount,
    ) {
        $this->currency = $currency;
        $this->amount = $amount;
    }
}
// 替换成
class Money 
{
    public function __construct(
        public Currency $currency,
        public int $amount,
    ) {}
}

6.nullsafe运算符

// 现在可以用新的 nullsafe 运算符链式调用,而不需要条件检查 null。 如果链条中的一个元素失败了,整个链条会中止并认定为 Null$country = null; if ($session !== null) { $user = $session->user; if ($user !== null) { $address = $user->getAddress(); if ($address !== null) { $country = $address->country; } } } // 简化为一行代码 $country = $session?->user?->getAddress()?->country;

7.str_contains()、str_starts_with()和str_ends_with()函数

// 不必再依赖strpos() 来知道字符串是否包含另一个字符串了。
if (strpos('最讨厌红色的衣服了', '红色') !== false) { /* … */ }
// 可以这样做
if (str_contains('最讨厌红色的衣服了', '红色')) { /* … */ }
// 感觉大多数场景应该是不需要使用strpos了吧,外两个早就应该有了,str_starts_with()和str_ends_with()这两个函数现在能省事不少。
str_starts_with('商品错误类型为 type error', '商品错误类型'); // true
str_ends_with('商品错误类型为 type error', 'type error'); // true

8.注解

// 现在可以用原生的PHP语法来使用结构化的元数据,而不需要再依赖PHPDoc解析,性能也随之提升。之前定义注解路由可能需要使用:
class PostsController
{
    /**
     * @Route("/api/posts/{id}", methods={"GET"})
     */
    public function get($id) { /* ... */ }
}
// 现在可以直接用PHP的注解语法来定义,并通过反射直接获取
class PostsController
{
    #[Route("/api/posts/{id}", methods: ["GET"])]
    public function get($id) { /* ... */ }
}

9.Match表达式

match可以返回值,不需要break语句,可以组合条件,使用严格的类型比较,并且不执行任何类型的强制。

$result = match($input) {
    0 => "hello",
    '1', '2', '3' => "world",
};

10.WeakMap

  • WeakMap保留对对象的引用,这些引用不会阻止这些对象被垃圾回收。
  • 以 ORM 为例,它们通常实现缓存,这些缓存保存对实体类的引用,以提高实体之间的关系性能。这些实体对象不能被垃圾回收,只要此缓存具有对它们的引用,即使缓存是唯一引用它们的对象。
  • 如果此缓存层使用弱引用和映射代替,PHP 将垃圾收集这些对象当再没有别的引用他们了。特别是在 ORM 的情况下,它可以管理请求中的数百个,如果不是数千个实体;weak maps可以提供更好、更资源友好的处理这些对象的方法。
class Foo 
{
    private WeakMap $cache;
 
    public function getSomethingWithCaching(object $obj): object
    {
        return $this->cache[$obj]
           ??= $this->computeSomethingExpensive($obj);
    }
}

11.0 == 'foobar' 返回false

// PHP7 
0 == 'foobar' // 返回true 
// PHP8 
0 == 'foobar' // 返回false

12.在对象上使用::class

现在可以对对象使用::class,它的工作方式与 get_class() 相同。

$foo = new Foo(); 
var_dump($foo::class);

13.traits 中的抽象方法改进

Traits 可以指定抽象方法,这些方法必须由使用它们的类实现。在PHP8,必须保持一致的方法定义,包括参数类型和返回类型。

trait MyTrait {
    abstract private function neededByTheTrait(): string;
 
    public function doSomething() {
        return strlen($this->neededByTheTrait());
    }
}
 
class TraitUser {
    use MyTrait;
 
    // This is allowed:
    private function neededByTheTrait(): string { }
 
    // This is forbidden (incorrect return type)
    private function neededByTheTrait(): stdClass { }
 
    // This is forbidden (non-static changed to static)
    private static function neededByTheTrait(): string { }
}

14.类型系统与错误处理的改进

  • 算术/位运算符更严格的类型检测
  • Abstract trait 方法的验证
  • 确保魔术方法签名正确 PHP
  • 引擎 warning 警告的重新分类
  • 不兼容的方法签名导致 Fatal 错误
  • 操作符 @ 不再抑制 fatal 错误
  • 私有方法继承
  • Mixed 类型
  • Static 返回类型
  • 内部函数的类型 Email thread
  • 扩展 Curl、 Gd、 Sockets、 OpenSSL、 XMLWriter、 XML 以 Opaque 对象替换 resource

15.其他语法调整和改进

  • 允许参数列表中的末尾逗号、闭包 use 列表中的末尾逗号
  • 无捕获的 catche
  • 变量语法的调整 Namespace
  • 名称作为单个 token
  • 现在 throw 是一个表达式
  • 允许对象的 ::class
标签: PHP
最后更新:2023年10月16日

酆叔

上辈子作恶多端,这辈子早起上班。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

最新 热点 随机
最新 热点 随机
2025/05/15 周四 晴 2025/05/12 周一 晴 2025/05/08 周四 多云 2025/05/07 周三 阵雨 2025/05/06 周二 阵雨 2025/04/30 周三 多云
认识PHP(一)基本介绍 PHP之访问修饰符 认识PHP(九)面对对象的五大基本基本原则 VPN\机场 安装MySql PHP之静态
腾讯云
又拍云
订阅
订阅

COPYRIGHT © 2024 酆叔のBlog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备2023016219号