什么是PHP 7.4中的空合并赋值?? =运算符


9

我刚刚看了有关即将推出的PHP 7.4功能的视频,并看到了这个??=新操作员。我已经知道??操作员了。有什么不同?

Answers:


10

文档

合并等于或?? =运算符是赋值运算符。如果left参数为null,则将right参数的值分配给left参数。如果该值不为null,则不执行任何操作。

例:

// The folloving lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';

因此,如果以前从未分配过值,那么基本上只是一种简写方式。


4
看起来我们在官方文档中发现了一个错字。The folloving lines...
帕维尔·林特

这两条线是否“相同”并不是100%准确,在第二种情况下,左侧仅被评估一次,因此效率更高
the_nuts

7

它最初是在PHP 7中发布的,允许开发人员简化isset()检查并结合三元运算符。例如,在PHP 7之前,我们可能有以下代码:

$data['username'] = (isset($data['username']) ? $data['username'] : 'guest');

PHP 7发布时,我们可以改为这样写:

$data['username'] = $data['username'] ?? 'guest';

但是,现在,当发布PHP 7.4时,可以进一步简化为:

$data['username'] ??= 'guest';

一种不起作用的情况是,如果您想为另一个变量分配值,那么您将无法使用此新选项。因此,尽管这很受欢迎,但可能会有一些有限的用例。



1

范例文件

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.