php8.0新特性

410 阅读3分钟

1.相对于以前的 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

2.最实用的特性:构造器属性提升、Nullsafe运算符、str_contains()、 str_starts_with()、 str_ends_with()

构造器属性提升这个新的语法糖来用来创建值对象或数据传输对象。不用为类属性和构造函数指定它们,
PHP 现在可以将它们合并为一个。-----------------以前
class Money 
{
    public Currency $currency;
 
    public int $amount;
 
    public function __construct(
        Currency $currency,
        int $amount,
    ) {
        $this->currency = $currency;
        $this->amount = $amount;
    }
}


-----------------PHP8class Money 
{
    public function __construct(
        public Currency $currency,
        public int $amount,
    ) {}
}

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




有些人可能会说它早就该有了,但我们终于不必再依赖strpos() 来知道字符串是否包含另一个字符串了。

代替如下:if (strpos('string with lots of words', 'words') !== false) { /* … */ }
你可以这样做if (str_contains('string with lots of words', 'words')) { /* … */ }感觉大多数场景应该是不需要使用strpos了吧,
外两个早就应该有了,str_starts_with()和str_ends_with()这两个函数现在能省事不少。str_starts_with('haystack', 'hay'); // true
str_ends_with('haystack', 'stack'); // true

3.最具潜力的特性:注解、Match表达式、WeakMap

注解现在可以用原生的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) { /* ... */ }
}

4.Match表达式 你可以称它为switch表达式的大哥:match可以返回值,不需要break语句, 可以组合条件,使用严格的类型比较,并且不执行任何类型的强制。

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

5.WeakMap

WeakMap保留对对象的引用,这些引用不会阻止这些对象被垃圾回收。

以 ORM 为例,它们通常实现缓存,这些缓存保存对实体类的引用,以提高实体之间的关系性能。这些实体对象不能被垃圾回收,只要此缓存具有对它们的引用,即使缓存是唯一引用它们的对象。

如果此缓存层使用弱引用和映射代替,PHP 将垃圾收集这些对象当再没有别的引用他们了。特别是在 ORM 的情况下,它可以管理请求中的数百个,如果不是数千个实体;weak maps可以提供更好、更资源友好的处理这些对象的方法。

下面是weak maps的示例:class Foo 
{
    private WeakMap $cache;
 
    public function getSomethingWithCaching(object $obj): object
    {
        return $this->cache[$obj]
           ??= $this->computeSomethingExpensive($obj);
    }
}

6.其它特性

0 == 'foobar' 终于返回了false我们知道在PHP7里面0 == 'foobar' // 返回true
现在终于看起来更比较符合逻辑了0 == 'foobar' // 返回false

可以在对象上使用::class一个小而有用的新特性:现在可以对对象使用::class,它的工作方式与 get_class() 相同。$foo = new Foo();

var_dump($foo::class);
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 { }
}