Home>Article> An overview of all new PHP 8 features and code examples

An overview of all new PHP 8 features and code examples

Susan Sarandon
Susan Sarandon forward
2020-10-30 14:39:48 7894browse

Overview of all new features and code examples of PHP 8

The official version of PHP 8 will be released soon: RC3 will be released on October 29th, RC4 will be released on November 12th, and RC4 will be released on November 26th The official version will be released on the same day (you can clickPHP 8 Release Scheduleto view).

So, it’s time to take a look at the new features coming to PHP 8. In this article we will show you all the new features of PHP 8 and the corresponding code examples.

Compile and install PHP 8

In order to facilitate running the sample code, before starting, we can compile and install PHP 8 RC2 version locally:

// 0、下载解压源码 wget https://downloads.php.net/~pollita/php-8.0.0RC2.tar.gz tar zxvf php-8.0.0RC2.tar.gz cd php-8.0.0RC2 // 1、生成 configure 文件 ./buildconf --force // 2、配置构建流程(最小化安装) ./configure --prefix=/usr/local/php8 \ --with-config-file-path=/usr/local/php8 \ --enable-cli \ --without-iconv // 3、构建 && 安装 make && sudo make install // 4、拷贝配置文件 sudo cp php.ini-development /usr/local/php8/php.ini

Installation After completion, ensure that PHP 8 has been successfully installed by verifying the version:

An overview of all new PHP 8 features and code examples

The local operating system is Mac. For Windows environment installation, please refer to this tutorial that previously introduced JIT:Compile and install PHP 8based on WSL virtual machine.

In order to facilitate calling the PHP 8 CLI interpreter, I configured an alias for it in the ZSH configuration file~/.zshrc:

alias php8="/usr/local/php8/bin/php"

Then runsource ~/.zshrcLet the above alias take effect. In the future, you can directly call the PHP 8 CLI interpreter throughphp8:

An overview of all new PHP 8 features and code examples

New sample project

Next, we create a newphp8-demoproject in PhpStorm to store the sample code of this tutorial, and add the PHP language level and command line The interpreters are all adjusted to PHP 8.0 so that PhpStorm supports the latest version of PHP (don’t know how to configure it? You can check it out in thePhpStormtutorial):

An overview of all new PHP 8 features and code examples

Then we can start our journey of exploring new features of PHP 8.

New support for union types

Union types allow a variable to have multiple types of values instead of one (refer to C language union types for easy understanding) ).

We write a sample code as follows:

number = $number; } public function getNumber(): int|float { return $this->number; } } /** * 我们可以传递浮点型和整型值到 Number 对象 */ $number = new Number(); $number->setNumber(5); var_dump($number->getNumber()); $number->setNumber(11.54); var_dump($number->getNumber()); exit;

The above code runs as follows:

An overview of all new PHP 8 features and code examples

New WeakMap feature

WeakMap allows you to create a mapping of objects to arbitrary values (similar toSplObjectStorage) without preventing the object used as the key from being garbage collected. If an object key is garbage collected, the corresponding key-value pair will be removed from the collection.

This new feature is very useful because developers don't have to worry about memory leaks in their code. Most PHP developers probably don't care about this, but you must be careful about this problem when you write long-running processes, such as when using ReactPHP for event-driven programming: with WeakMap, the referenced object will automatically expire when it expires. Got garbage collected.

If you do the same thing in an array, you will still hold a reference to the object, causing a memory leak.

We write a sample code as follows:

cache = new WeakMap(); } public function getSomethingWithCaching(object $obj) { return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj); } public function computeSomethingExpensive(object $obj) { var_dump("I got called"); return rand(1, 100); } } $cacheObject = new stdClass; $obj = new FooBar; // "I got called" 只会打印一次 $obj->getSomethingWithCaching($cacheObject); $obj->getSomethingWithCaching($cacheObject); var_dump(count($obj->cache)); // 删除该对象后 WeakMap 会释放相应内存 unset($cacheObject); var_dump(count($obj->cache)); exit;

The corresponding running results are as follows:

An overview of all new PHP 8 features and code examples

New ValueError exception

PHP 8 introduces a new built-in exception class namedValueError, which inherits from theExceptionbase class. This exception will be thrown every time you pass a value to a function that is of an invalid type. Before PHP 8, such an operation would result in a warning.

The following is a sample code:


      

The running results are as follows:

An overview of all new PHP 8 features and code examples

Allow variable parameters when overriding methods

When we override a parent class method in a subclass, any number of parameters can now be replaced with variable parameters, as long as the corresponding parameter types are compatible:

method('i can be overwritten!'); exit;

The running results are as follows:

An overview of all new PHP 8 features and code examples

static return type

In PHP 8, you can use thestatickeyword to identify a certain A method returns the class that the method currently belongs to, even if it is inherited (late static binding):


      

Class name literal of the object

In PHP 8 You can use$object::classto get the class name of the object. The return result is the same asget_class($object):


      

The running result is as follows:

An overview of all new PHP 8 features and code examples

Variable syntax adjustment

newinstanceof关键字现在可以被用于任意表达式:


      

运行结果如下:

An overview of all new PHP 8 features and code examples

Stringable 接口

PHP 8 引入了新的Stringable接口,只要某个类实现了__toString方法,即被视作自动实现了Stringable接口(咋和 Go 接口实现有点像),而不必显式声明实现该接口:


      

运行结果如下:

An overview of all new PHP 8 features and code examples

Trait 现在可以定义抽象私有方法

neededByTheTrait()); } } class TraitUser { use MyTrait; // 支持该语法 private function neededByTheTrait(): string { } // 不支持该语法 (错误的返回类型) // private function neededByTheTrait(): stdClass { } // 支持该语法 (非静态方法变成了静态方法) // private static function neededByTheTrait(): string { } } exit;

throw 现在可以被用作表达式

throw语句现在可以用在只允许表达式出现的地方,例如箭头函数、合并运算符和三元运算符等:

 throw new Exception(); $nullableValue = null; // $value 是非空的 $value = $nullableValue ?? throw new \InvalidArgumentException(); exit;

参数列表中允许出现可选的尾部逗号

和数组中的尾部逗号类似,现在也可以在参数列表中定义一个尾部逗号:


      

上述代码运行结果是正常的:

An overview of all new PHP 8 features and code examples

捕获异常而不存储到变量

现在可以编写catch (Exception)代码来捕获异常而不必将其存储到一个变量中:


      

上述代码运行结果如下:

An overview of all new PHP 8 features and code examples

新增对mixed类型的支持

PHP 8 引入了新的名为mixed的类型,该类型等价于 array|bool|callable|int|float|null|object|resource|string


      

上述代码运行结果如下:

An overview of all new PHP 8 features and code examples

新增对注解的支持

PHP 8 的注解实际上包含了多个 RFC:

  • https://wiki.php.net/rfc/attributes_v2
  • https://wiki.php.net/rfc/attribute_amendments
  • https://wiki.php.net/rfc/shorter_attribute_syntax
  • https://wiki.php.net/rfc/shorter_attribute_syntax_change

注解绝对是 PHP 8 引入的最大新特性之一,一开始理解起来可能有点困难(不过有 Java 基础的话会很简单)。简而言之,注解允许你添加元数据到 PHP 函数、参数、类等,这些元数据随后可以通过可编程方式获取,在 PHP 7 或者更低版本中实现类似功能需要解析代码注释块,而通过注解可以直接访问深度集成到 PHP 自身的这些信息。

我们来编写一段示例代码方便你理解,假设你想要允许开发者添加中间件到控制器类/方法,使用注解可以这么做:

middleware = $middleware; } } // 下面的语法会添加上述注解到 MyController 类,并且传入 auth 作为参数 #[ApplyMiddleware('auth')] class MyController { public function index() { } } // 然后我们就可以在类中使用反射获取所有的 ApplyMiddleware 注解并读取给定的中间件参数 $reflectionClass = new ReflectionClass(MyController::class); $attributes = $reflectionClass->getAttributes(ApplyMiddleware::class); foreach ($attributes as $attribute) { $middlewareAttribute = $attribute->newInstance(); var_dump($middlewareAttribute->middleware); } exit;

运行上述代码,打印结果如下:

An overview of all new PHP 8 features and code examples

新增构造函数属性提示支持

这个新特性只是一个语法简写而言,可以将属性声明和构造函数属性初始化合并到一起:

id); var_dump($user->name); exit;

上述代码运行结果如下:

An overview of all new PHP 8 features and code examples

新增match表达式支持

match表达式和switch分支语句类型,但是语义上更加安全并且可以直接返回值:

 'Foo', 1 => 'Bar', 2 => 'Baz', }; exit;

上述代码运行结果如下:

An overview of all new PHP 8 features and code examples

新增对空安全运算符?->的支持

当该运算符的左侧评估为 null 时,整个代码链路的执行将会被终止并整体评估为 null。如果不为 null 的话,则和普通的->运算符功能一致:

getAddress()?->country?->iso_code; var_dump($country); exit;

上述代码运行结果如下:

An overview of all new PHP 8 features and code examples

新增对命名参数的支持

命名参数允许基于参数名称传递参数到函数,而不是参数所在的位置,这样一来,函数参数就可以自解释并且与顺序无关,并且允许跳过默认值:


      

注:PHP 8 还有另一个重要的新特性 —— 引入对 JIT 的支持,不过对于上层业务代码而言是无感的,只是底层优化而已,想要了解 JIT 对 PHP 应用性能的影响,请参考之前发布的这篇文章:https://xueyuanjun.com/post/21702。本篇教程所有示例代码整理自 PHP 8 - try out all new features,原文基于 Laravel 框架进行测试,这里将其转化为了通用的 PHP 代码


Statement:
This article is reproduced at:xueyuanjun.com. If there is any infringement, please contact admin@php.cn delete