Home > Backend Development > PHP Tutorial > Do you know what are the new features of PHP 7.4?

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

慕斯
Release: 2023-04-10 07:02:02
forward
2306 people have browsed it

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);
Copy after login

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

$arr = [...$args];
Copy after login
## 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);
Copy after login

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
Copy after login

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"
  }
Copy after login

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];
Copy after login

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'];
Copy after login

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"
}
Copy after login

We can also use generators:

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

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

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

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
Copy after login

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;];
Copy after login

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"
  }
Copy after login

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);
Copy after login

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);
Copy after login

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;
  };
Copy after login

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;
Copy after login

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;;
Copy after login
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;;
Copy after login

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’;
Copy after login

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;
  }
Copy after login

除了 voidcallable 外,所有的类型都支持

  public int $scalarType;
  protected ClassName $classType;
  private ?ClassName $nullableClassType;
Copy after login

为什么不支持 voidcallable?下面是 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;
Copy after login

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

  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
Copy after login

弱引用

在这个 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
Copy after login

协变返回和逆变参数

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

  • 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;
}
Copy after login

逆变参数:

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

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

预加载

这个 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.iniopcache.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;
Copy after login

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

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

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

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

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

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

这个提案分为两步走:

  • 从 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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template