我刚刚看到了一个关于即将推出的PHP 7.4功能的视频,并且看到了这个新的
??=
操作符。我已经知道 ??
操作符了。
这个操作符有什么区别呢?根据文档:
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';
所以它基本上只是一种简写方式,用于在之前没有赋值的情况下为变量赋值。
空值合并赋值运算符是一种简写方式,用于将空值合并运算符的结果赋值给变量。
以下是官方发布说明中的示例(英文链接):
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
空值合并赋值运算符链:
$a = null;
$b = null;
$c = 'c';
$a ??= $b ??= $c;
print $b; // c
print $a; // c
??
。 空合并赋值运算符的重点是它可以处理未定义的变量。 因此,您可以删除前两行将 null 赋值给 $a 和 $b 的代码,该代码仍将正常工作。 - pbarney示例 文档:
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
$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);
}
它大致可以翻译为"$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
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" );
我仍然使用它,因为它更易读。