PHP 7.4中的null coalescing assignment ??=运算符是什么?

73
我刚刚看到了一个关于即将推出的PHP 7.4功能的视频,并且看到了这个新的 ??= 操作符。我已经知道 ?? 操作符了。 这个操作符有什么区别呢?

13
“$foo = $foo ?? 'bar'” 可以简写为 “$foo ??= 'bar'”。 - Gazzer
6个回答

56

根据文档

Coalesce equal 或 ??= 操作符是一个赋值操作符,如果左参数为 null,则将右参数的值赋给左参数。如果左参数的值不为 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';

所以它基本上只是一种简写方式,用于在之前没有赋值的情况下为变量赋值。


7
看起来我们在官方文档中发现了一个错别字。“The folloving lines...”应该改为“The following lines...”。 - Pavel Lint
2
翻译:并不是两行代码完全“相同”,在第二种情况下,左侧只被计算一次,因此更有效率。 - the_nuts
如果左参数为空,则分配(...)。你不觉得应该更正为:如果左参数为空或未设置,则分配(...)吗? - Dawid Ohia

9

空值合并赋值运算符是一种简写方式,用于将空值合并运算符的结果赋值给变量。

以下是官方发布说明中的示例(英文链接)

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}

7

空值合并赋值运算符链:

$a = null;
$b = null;
$c = 'c';

$a ??= $b ??= $c;

print $b; // c
print $a; // c

Example at 3v4l.org


3
由于所有变量都已定义,因此该示例可以轻松处理空合并运算符 ??。 空合并赋值运算符的重点是它可以处理未定义的变量。 因此,您可以删除前两行将 null 赋值给 $a 和 $b 的代码,该代码仍将正常工作。 - pbarney

2

示例 文档

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}

0
你可以在循环的第一次迭代中使用这个来初始化变量。但要小心!
$reverse_values = array();
$array = ['a','b','c']; // with [NULL, 'b', 'c'], $first_value === 'b'
foreach($array as $key => $value) {
  $first_value ??= $value; // won't be overwritten on next iteration (unless 1st value is NULL!)
  $counter ??= 0; // initialize counter
  $counter++;
  array_unshift($reverse_values,$value);
}
// $first_value === 'a', or 'b' if first value is NULL
// $counter === 3
// $reverse_values = array('c','b','a'), or array('c','b',NULL) if first value is null

如果第一个值是NULL,那么$first_value将被初始化为NULL,然后被下一个非NULL值覆盖。如果数组有很多NULL值,$first_value最终将成为NULL或最后一个NULL后的第一个非NULL值。所以这似乎是一个可怕的想法。
我仍然更喜欢像这样做,主要是因为它更清晰,但也因为它可以处理NULL作为数组值:
$reverse_values = array();
$array = ['a','b','c']; // with [NULL, 'b', 'c'], $first_value === NULL
$counter = 0;
foreach($array as $key => $value) {
  $counter++;
  if($counter === 1) $first_value = $value; // does work with NULL first value
  array_unshift($reverse_values,$value);
}

0

它大致可以翻译为"$a默认为$b",就像这样:

$page ??= 1;            //  If page is not specified, start at the beginning
$menu ??= "main";       //  Default menu is the main menu
$name ??= "John Doe";   //  Name not given --> use John Doe

在PHP世界中期待已久的工具。
在PHP 7.4之前,我们使用一个函数来实现这个功能:
function defaultOf(&$var, $value) {
    if(is_null($var)) $var=$value;
}

// Now the 3 statements above would look like:

defaultOf( $page, 1 );
defaultOf( $menu, "main" );
defaultOf( $name, "John Doe" );

我仍然使用它,因为它更易读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接