发布于 2026-01-06 0 阅读
0

PHP 8 新特性及与旧版本的对比。DEV 全球项目展示挑战赛,由 Mux 主办:快来展示你的项目吧!

PHP 8 新特性及与旧版本的比较。

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

PHP 8.0 是 PHP 语言的一次重大更新。
它包含许多新特性和优化,包括命名参数、联合类型、属性、构造函数属性提升、匹配表达式、空安全运算符、JIT,以及类型系统、错误处理和一致性方面的改进……

目录

===

  1. JIT编译器。
  2. PHP 8 新特性。
  3. PHP 8 的影响和兼容性(与 WordPress)。
  4. 已弃用的功能。

1. JIT(即时)编译器


PHP 代码运行时,通常是在虚拟机中编译并执行。JIT(即时编译器)会改变这一现状,它将代码编译成 x86 机器代码,然后直接在 CPU 上运行。对于大量依赖数学函数的应用程序来说
,这应该可以提升性能。

这是 PHP 8 中最重要的新特性更新之一:JIT 默认情况下未启用。然而,JIT 对 Web 应用程序的影响并不大。

JIT性能示例:

参考资料:PHP 8 - 新功能、改进和 WordPress 潜在问题

2. PHP 8 新特性

===
感谢:

空安全运算符 RFC

与其写传统的 !== null,不如使用“?”运算符,这样只需一行代码,应用程序的功能就变得非常清晰了:

前:



$country =  null;

if ($session !== null) {
  $user = $session->user;

  if ($user !== null) {
    $address = $user->getAddress();

    if ($address !== null) {
      $country = $address->country;
    }
  }
}


Enter fullscreen mode Exit fullscreen mode

后:



$country = $session?->user?->getAddress()?->country;


Enter fullscreen mode Exit fullscreen mode

建筑商房地产推广

PHP 现在可以将类属性和构造函数合并为一个,而无需再分别指定它们。



// In php 7.x
class Point {
    protected float $x;
    protected float $y;
    protected float $z;

    public function __construct(
        float $x = 0.0,
        float $y = 0.0,
        float $z = 0.0,
    ) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }
}

// In PHP 8
class Point {
    public function __construct(
        protected float $x = 0.0,
        protected float $y = 0.0,
        protected float $z = 0.0,
    ) {}
}


Enter fullscreen mode Exit fullscreen mode

联合类型 2.0 RFC

PHP 是一种动态类型系统,因此联合类型在很多情况下都非常有用。联合类型是两种或多种类型的集合,表明其中任何一种类型都可以使用。



// In PHP 7.4
class Number {
    private $number;

    public function setNumber($number) {
        $this->number = $number;
    }
}

// In PHP 8
class Number {
    private int|float $number;

    public function setNumber(int|float $number): void {
        $this->number = $number;
    }
}


Enter fullscreen mode Exit fullscreen mode

混合型RFC

参考链接

混合类型是对 PHP8 类型系统的良好补充。它等同于以下类型之一。



  array|bool|callable|int|float|null|object|resource|string


Enter fullscreen mode Exit fullscreen mode

以下是 RFC 文档中关于如何使用此功能的示例:



public function foo(mixed $value) {}


Enter fullscreen mode Exit fullscreen mode

另请注意,由于 mixed 类型已经包含 null 值,因此不允许将其设置为可为空。以下操作将触发错误:



// Fatal error: Mixed types cannot be nullable, null is already part of the mixed type.
function bar(): ?mixed {}


Enter fullscreen mode Exit fullscreen mode

匹配表达式RFC

match表达式是否可以替代switch语句?match表达式可以返回值,而且不像switch语句那样需要冗长的语句。它使用严格的类型比较。



//The switch statement loosely compares (==) the given value to the case values. This can lead to some very surprising results.
switch ('100') {
  case 100:
    $price = "Oh no!";
    break;
  case '100':
    $price = "This is what I expected";
    break;
}
echo $price;
///> Oh no!

//The match expression uses strict comparison (===) instead. The comparison is strict regardless of strict_types.
echo match ('100') {
  100 => "Oh no!",
  '100' => "This is what I expected",
};


Enter fullscreen mode Exit fullscreen mode

命名参数RFC

命名参数让函数调用更加灵活。以前,你必须调用函数并按照函数指定的顺序传递每个参数。



class ExampleClass {

  public function __construct(
      private string $title, 
      private string|null $description, 
      private string $type ) {

  }
}

// In  PHP 7.x
$my_class = new Log (
  'New Support request',
  '',
  'support',
);

// In PHP 8
$my_class = new ExampleClass (
  title : 'New Support request',
  description : 'You received a new support ...',
  type: 'support',
);

// even you can write something like these
$my_class = new ExampleClass (
  title : 'New Support request',
  type: 'support',
);


Enter fullscreen mode Exit fullscreen mode

属性

现在,您可以使用 PHP 的原生语法来编写结构化元数据,而无需使用 PHPDoc 注解。



// PHP 7
{
    /**
     * @Route("/api/posts/{id}", methods={"GET"})
     */
    public function get($id) { /* ... */ }
}

// PHP 8
class PostsController
{
    #[Route("/api/posts/{id}", methods: ["GET"])]
    public function get($id) { /* ... */ }
}


Enter fullscreen mode Exit fullscreen mode

PHP 新函数和类

新增类、接口和函数

  • 属性 v2 RFC
  • 弱映射RFC
  • 抛出表达式RFC
  • 参数列表中末尾缺少逗号。```php

class Comment {
public function __construct(
string $titla,
string $description,
int $status, // 末尾逗号
) {
// 执行某些操作
}
}

- Inheritance with private methods [RFC](https://wiki.php.net/rfc/inheritance_private_methods).
- Arrays Starting With a Negative Index.
```php


$book = array_fill(-4, 6, 'title');
var_dump($book);
//output 
array(6) {
  [-4]=>
  string(5) "title"
  [-3]=>
  string(5) "title"
  [-2]=>
  string(5) "title"
  [-1]=>
  string(5) "title"
  [0]=>
  string(5) "title"
  [1]=>
  string(5) "title"
}

// In PHP 7.4 like these
//output 
array(6) {
  [-4]=>
  string(5) "title"
  [0]=>
  string(5) "title"
  [1]=>
  string(5) "title"
  [2]=>
  string(5) "title"
  [3]=>
  string(5) "title"
  [4]=>
  string(5) "title"
}
=> null


Enter fullscreen mode Exit fullscreen mode
  • 非捕获式RFC ```php

//PHP 8 之前
版本 try {
AddUser();
} catch (PermissionException $ex) {
echo "您没有添加用户的权限";
}

//PHP 8
try {
AddUser();
} catch (PermissionException) { //意图很明确:异常详情无关紧要
echo "您没有添加用户的权限";
}

- ...

### 3. PHP 8 impact & compatibility (with Wordpress).
===
[Reference Link](https://developer.yoast.com/blog/the-2020-wordpress-and-php-8-compatibility-report/)

[Wordpress Version Compatibility](https://make.wordpress.org/core/handbook/references/php-compatibility-and-wordpress-versions/)

PHP 8 is a major update of PHP and WordPress aims to always be compatible with new versions of PHP.

Only a small percentage of the available plugins, the more popular and professionally developed ones, have automated tests in place.

PHP 7.* versions have seen a far larger set of deprecations than previous versions of PHP. Where PHP 5.6 to PHP 7 was a relatively simple migration, going from 7.x to 8 could be very painful, especially for very old codebases, the reality, however, is that WordPress is not such a codebase.

#### The test report is:

** Issues reported early on in the WP 5.6 dev cycle and fixed since based on PHPCompatibility scans:

- [Optional parameters declared before required parameters](https://core.trac.wordpress.org/ticket/50343)
- [Final private methods](https://core.trac.wordpress.org/ticket/50897)
- [Remove use of create_function](https://core.trac.wordpress.org/ticket/50899)
- [Only call libxmldisableentity_loader conditionally](https://core.trac.wordpress.org/ticket/50898)


** There are a large number of PHP warnings that have been changed to error exceptions in PHP 8. 

** Error level changes unrelated to RFC’s
The following warnings have been converted to errors probably related to deprecations in PHP 7.x versions:

- Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
- Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
- Attempting to use an invalid type (array or object) as an array key or string offset.
- Attempting to write to an array index of a scalar value.
- Attempting to unpack a non-array/Traversable.

** Warnings coming from anywhere

PHP 8 is going to contain a lot of breaking changes and focusing so strongly on strict typing, WordPress’ type unsafe extensibility system also becomes extra vulnerable to errors, potentially leading to plugins causing type errors in other plugins or WordPress itself, many warnings that will turn into errors with PHP 8.

### 4. Deprecated

During the PHP 7.x release cycle, each version introduced new deprecations, which have now been finalized as feature removals in PHP 8. This also applies to some deprecation which were already put in place in PHP 5.x, but weren't removed in the PHP 7.0 release.

- php_errormsg.
- create_function().
- mbstring.func_overload.
- parse_str() without second argument.
- each().
- assert() with string argument.
- $errcontext argument of error handler.
- String search functions with integer needle.
- Defining a free-standing assert() function.
- The real type (alias for float).
- Magic quotes legacy.
- array_key_exists() with objects.
- Reflection export() methods.
- implode() parameter order mix.
- Unbinding $this from non-static closures.
- restore_include_path() function.
- allow_url_include ini directive.
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/dannyviiprus/php-8-new-features-comparison-with-older-versions-1ljj