search
HomeBackend DevelopmentPHP TutorialDo you know what are the new features of PHP 7.4?

There are so many things that we need to learn and understand in PHP. In today’s article, let’s take a look at the secrets in php7.4! I believe that you will gain a lot after reading this article. Without further ado, let’s take a look!

Do you know what are the new features of PHP 7.4?

What’s new in PHP in PHP 7.4?

In this article, we discuss some changes and features that should be added to the language in the final version of PHP 7.4:

  • Support for unpacking within arrays – Array expansion Spread operator
  • Arrow functions 2.0 (shorter closures)
  • NULL coalescing operator
  • Weak references
  • Covariant returns and contravariant parameters
  • Preloading
  • New custom object serialization mechanism

Performance improvement, the Spread operator is introduced in array expressions...

Available since PHP 5.6 , parameter unpacking is the syntax for unpacking arrays and Traversables into parameter lists. To unpack an array or Traversable, it must be prefixed with ... (3 dots), as in the following example:

function test(...$args) { var_dump($args); }
test(1, 2, 3);

However, the PHP 7.4 RFC recommends extending this functionality to arrays:

$arr = [...$args];
## The first benefit of

#Spread operator is performance. The RPC documentation states:

Spread operator should have better performance than

array_merge. It's not just that the Spread operator is a syntax construct, but array_merge is a method. Also at compile time, constant arrays are optimized for high efficiency.

One significant advantage of the Spread operator is that it supports any traversable object, while the

array_merge function only supports array. Here is an example of parameters in an array with the Spread operator:

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);

If you run this code in PHP 7.3 or earlier, PHP will throw a Parse error:

Parse error: syntax error, unexpected '...' (T_ELLIPSIS), expecting ']' in /app/spread-operator.php on line 3

Instead, PHP 7.4 will return an array

array(5) {
    [0]=>
    string(6) "banana"
    [1]=>
    string(6) "orange"
    [2]=>
    string(5) "apple"
    [3]=>
    string(4) "pear"
    [4]=>
    string(10) "watermelon"
  }

RFC states that we can extend the same array multiple times. Furthermore, we can use the Spread Operator syntax anywhere in the array since regular elements can be added before or after the spread operator. Therefore, the following code will work as expected:

$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = [...$arr1, ...$arr2];
$arr4 = [...$arr1, ...$arr3, 7, 8, 9];

It is also possible to pass the array returned by the function as a parameter and put it into a new array:

function buildArray(){
    return ['red', 'green', 'blue'];
}
$arr1 = [...buildArray(), 'pink', 'violet', 'yellow'];

PHP 7.4 outputs the following array:

array(6) {
    [0]=>
    string(3) "red"
    [1]=>
    string(5) "green"
    [2]=>
    string(4) "blue"
    [3]=>
    string(4) "pink"
    [4]=>
    string(6) "violet"
    [5]=>
    string(6) "yellow"
}

We can also use generators:

  function generator() {
    for ($i = 3; $i <= 5; $i++) {
        yield $i;
    }
  }
  $arr1 = [0, 1, 2, ...generator()];

But passing by reference is not allowed. Consider the following example:

$arr1 = [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;];
$arr2 = [...&$arr1];

If we try to pass by reference, PHP will throw the following Parse error:

Parse error: syntax error, unexpected &#39;&&#39; in /app/spread-operator.php on line 3

If the elements of the first array are stored by reference, then They are also stored by reference in the second array. Here is an example:

  $arr0 = &#39;red&#39;;
  $arr1 = [&$arr0, &#39;green&#39;, &#39;blue&#39;];
  $arr2 = [&#39;white&#39;, ...$arr1, &#39;black&#39;];

This is what we get with PHP 7.4:

  array(5) {
    [0]=>
    string(5) "white"
    [1]=>
    &string(3) "red"
    [2]=>
    string(5) "green"
    [3]=>
    string(4) "blue"
    [4]=>
    string(5) "black"
  }

Arrow Functions 2.0 (Short Closure)

In PHP In , anonymous functions are considered to be very verbose and difficult to implement and maintain, and the RFC recommends introducing a simpler and clearer arrow function (or short closure) syntax so that we can write code concisely. Before PHP 7.4:

  function cube($n){
    return ($n * $n * $n);
  }
  $a = [1, 2, 3, 4, 5];
  $b = array_map(&#39;cube&#39;, $a);
  print_r($b);

PHP 7.4 allows for a more concise syntax, the above function can be rewritten as follows:

  $a = [1, 2, 3, 4, 5];
  $b = array_map(fn($n) => $n * $n * $n, $a);
  print_r($b);

Currently, due to the language structure, anonymous functions (closures) can be used

use Inherit variables defined in the parent scope as follows:

  $factor = 10;
  $calc = function($num) use($factor){
    return $num * $factor;
  };

But in PHP 7.4, the value of the parent scope is captured implicitly (implicitly by value scope to bind). So we can use one line to complete this function

  $factor = 10;
  $calc = fn($num) => $num * $factor;

Variables defined in the parent scope can be used for arrow functions. It is equivalent to our use of

use and cannot be used Modified by the parent. The new syntax is a great improvement to the language, as it allows us to build more readable and maintainable code.

NULL coalescing operator

Due to the large number of situations where ternary expressions and isset () are used simultaneously in daily use, we added the null coalescing operator (??) Syntactic sugar. If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.

  $username = $_GET[&#39;user&#39;] ?? ‘nobody&#39;;
What this code does is very simple:

It gets the request parameter and sets a default value if it doesn't exist . But in this RFC example, what if we have longer variable names?

$this->request->data[&#39;comments&#39;][&#39;user_id&#39;] = $this->request->data[&#39;comments&#39;][&#39;user_id&#39;] ?? &#39;value&#39;;

In the long run, this code may be difficult to maintain. Therefore, aiming to help developers write more intuitive code, this RFC proposes to introduce the null coalesce equal operator (null_coalesce_equal_operator)

??=, so we can type the following code to replace the above code :

  $this->request->data[&#39;comments&#39;][&#39;user_id&#39;] ??= ‘value’;

If the value of the left parameter is

null, the value of the right parameter is used.

Note that although the coalesce operator

?? is a comparison operator, ??= is an assignment operator.

类型属性 2.0

类型的声明,类型提示,以及指定确定类型的变量传递给函数或类的方法。其中类型提示是在 PHP5 的时候有的一个功能,PHP 7.2 的时候添加了 object 的数据类型。而 PHP7.4 更是增加了主类属性声明,看下面的例子:

  class User {
    public int $id;
    public string $name;
  }

除了 void 和 callable 外,所有的类型都支持

  public int $scalarType;
  protected ClassName $classType;
  private ?ClassName $nullableClassType;

为什么不支持 void 和 callable?下面是 RFC 的解释

The void type is not supported, because it is not useful and has unclear semantics.
不支持 void 类型,是因为它没用,并且语义不清晰。

The callable type is not supported, because its behavior is context dependent.
不支持 callable 类型,因为其行为取决于上下文。

因此,我们可以放心使用 boolintfloatstringarrayobjectiterableselfparent,当然还有我们很少使用的 nullable 空允许 (?type)

所以你可以在 PHP7.4 中这样敲代码:

  // 静态属性的类型
  public static iterable $staticProp;

  // var 中声明属性
  var bool $flagl

  // 设置默认的值
  // 注意,只有 nullable 的类型,才能设置默认值为 null
  public string $str = "foo";
  public ?string $nullableStr = null;

  // 多个同类型变量的声明
  public float $x, $y;

如果我们传递不符合给定类型的变量,会发生什么?

  class User {
    public int $id;
    public string $name;
  }

  $user = new User;
  $user->id = 10;
  $user->name = [];

  // 这个会产生一个致命的错误
  Fatal error: Uncaught TypeError: Typed property User::$name must be string, array used in /app/types.php:9

弱引用

在这个 RFC 中,提议引入 WeakReference 这个类,弱引用允许编码时保留对对象的引用,该引用不会阻止对象被破坏;这对于实现类似于缓存的结构非常有用。

该提案的作者 Nikita Popov 给出的一个例子:

  $object = new stdClass;
  $weakRef = WeakReference::create($object);

  var_dump($weakRef->get());
  unset($object);
  var_dump($weakRef->get());

  // 第一次 var_dump
  object(stdClass)#1 (0) {}

  // 第二次 var_dump,当 object 被销毁的时候,并不会抛出致命错误
  NULL

协变返回和逆变参数

协变和逆变
百度百科的解释

  • Invariant (不变): 包好了所有需求类型
  • Covariant (协变):类型从通用到具体
  • Contravariant (逆变): 类型从具体到通用目前,PHP 主要具有 Invariant 的参数类型,并且大多数是 Invariant 的返回类型,这就意味着当我是 T 参数类型或者返回类型时,子类也必须是 T 的参数类型或者返回类型。但是往往会需要处理一些特殊情况,比如具体的返回类型,或者通用的输入类型。而 RFC 的这个提案就提议,PHP7.4 添加协变返回和逆变参数,以下是提案给出来的例子:协变返回:
interface Factory {
  function make(): object;
}

class UserFactory implements Factory {
  // 将比较泛的 object 类型,具体到 User 类型
 function make(): User;
}

逆变参数:

interface Concatable {
  function concat(Iterator $input); 
}

class Collection implements Concatable {
  // 将比较具体的 `Iterator`参数类型,逆变成接受所有的 `iterable`类型
  function concat(iterable $input) {/* . . . */}
}

预加载

这个 RFC 是由 Dmitry Stogov 提出的,预加载是在模块初始化的时候,将库和框架加载到 OPCache 中的过程,如下图所示

引用他的原话:

On server startup – before any application code is run – we may load a certain set of PHP files into memory – and make their contents “permanently available” to all subsequent requests that will be served by that server. All the functions and classes defined in these files will be available to requests out of the box, exactly like internal entities.
服务器启动时 – 在运行任何应用程序代码之前 – 我们可以将一组 PHP 文件加载到内存中 – 并使得这些预加载的内容,在后续的所有请求中 “永久可用”。这些文件中定义的所有函数和类在请求时,就可以开箱即用,与内置函数相同。

预加载由 php.ini 的 opcache.preload 进行控制。这个参数指定在服务器启动时编译和执行的 PHP 脚本。此文件可用于预加载其他文件,或通过 opcache_compile_file() 函数

这在性能上有很大的提升,但是也有一个很明显的缺点,RFC 提出来了

preloaded files remain cached in opcache memory forever. Modification of their corresponding source files won’t have any effect without another server restart.

预加载的文件会被永久缓存在 opcache 内存中。在修改相应的源文件时,如果没有重启服务,修改就不会生效。

新的自定义对象序列化机制 

这是尼基塔·波波夫(Nikita Popov)的另一项建议 ,得到了绝大多数票的批准。

当前,我们有两种不同的机制可以在PHP中对对象进行自定义序列化:

  • __sleep()__wakeup()魔术方法
  • Serializable接口

根据Nikita的说法,这两个选项都存在导致复杂且不可靠的代码的问题。 您可以在RFC中深入研究此主题。 在这里,我只提到新的序列化机制应该通过提供两个结合了两个现有机制的新魔术方法__serialize()__unserialize()来防止这些问题。

该提案以20票对7票获得通过。

PHP7.4 又将废弃什么功能呢?

更改连接运算符的优先级

目前,在 PHP 中 + , - 算术运算符和 . 字符串运算符是左关联的, 而且它们具有相同的优先级。例如:

  echo "sum: " . $a + $b;

在 PHP 7.3 中,此代码生成以下警告:

  Warning: A non-numeric value encountered in /app/types.php on line 4

这是因为这段代码是从左往右开始的,所以等同于:

  echo ("$sum: " . $a) + $b;

针对这个问题,这个 RFC 建议更改运算符的优先级,使 . 的优先级低于 + ,- 这两个运算符,以便在字符串拼接之前始终执行加减法。所以这行代码应该等同于以下内容:

  echo "$sum: " . ($a + $b);

这个提案分为两步走:

  • 从 PHP7.4 开始,当遇见 + - 和 . 在没有指明执行优先级时,会发出一个弃用通知。
  • 而真正调整优先级的这个功能,会在 PHP8 中执行弃用左关联三元运算符在 PHP 中,三元运算符与许多其他语言不同,它是左关联的。而根据 Nikita Popof 的所说:对于在不同语言之间切换的编程人员来说,会令他们感到困扰。比如以下的例子,在 PHP 中是正确的:$b = $a == 1 ? 'one' : $a == 2 ? 'two' : $a == 3 ? 'three' : 'other';它会被解释为:$b = (($a == 1 ? 'one' : $a == 2) ? 'two' : $a == 3) ? 'three' : 'other';对于这种复杂的三元表现形式,它很有可能不是我们希望的方式去工作,容易造成错误。因此,这个 RFC 提议删除并弃用三元运算符的左关联使用,强制编程人员使用括号。这个提议分为两步执行:
  • 从 PHP7.4 开始,没有明确使用括号的嵌套三元组将抛出弃用警告。
  • 从 PHP 8.0 开始,将出现编译运行时错误。

php7.4性能

出于对PHP 7.4的Alpha预览版性能状态的好奇,我今天针对使用Git构建的PHP 7.3.6、7.2.18、7.1.29和7.0.32运行了一些快速基准测试,并且每个发行版均以相同的方式构建。

在此阶段,PHPBench的7.4性能与PHP 7.3稳定版相当,已经比PHP 7.0快了约30%…当然,与PHP 5.5的旧时代相比,收益甚至更大。

在微基准测试中,PHP 7.4的运行速度仅比PHP 7.3快一点,而PHP-8.0的性能却差不多,至少要等到JIT代码稳定下来并默认打开为止。

在Phoronix测试套件的内部PHP自基准测试中,PHP 7.4的确确实处于PHP 7.3性能水平之上-至少在此Alpha前状态下。 自PHP 7.0起,取得了一些显着的进步,而自PHP5发行缓慢以来,也取得了许多进步。

总结:PHP7.4是一个令人期待的版本,但是PHP8才是整个PHP界最重大的事情。

推荐学习:《PHP视频教程

 

The above is the detailed content of Do you know what are the new features of PHP 7.4?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version