我刚刚看了有关即将推出的PHP 7.4功能的视频,并看到了这个??=新操作员。我已经知道??操作员了。有什么不同?
Ram*_*mki 22
在PHP 7 中,这最初是发布的,允许开发人员结合三元运算符来简化 isset() 检查。例如,在 PHP 7 之前,我们可能有这样的代码:
$data['username'] = (isset($data['username']) ? $data['username'] : 'guest');
Run Code Online (Sandbox Code Playgroud)
当PHP 7发布时,我们可以将其写为:
$data['username'] = $data['username'] ?? 'guest';
Run Code Online (Sandbox Code Playgroud)
然而,现在,当PHP 7.4发布时,这可以进一步简化为:
$data['username'] ??= 'guest';
Run Code Online (Sandbox Code Playgroud)
这不起作用的一种情况是,如果您想为不同的变量分配一个值,那么您将无法使用这个新选项。因此,虽然这很受欢迎,但可能有一些有限的用例。
小智 7
空合并赋值运算符链接:
$a = null;
$b = null;
$c = 'c';
$a ??= $b ??= $c;
print $b; // c
print $a; // c
Run Code Online (Sandbox Code Playgroud)
从文档:
合并等于或?? =运算符是赋值运算符。如果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';
Run Code Online (Sandbox Code Playgroud)
因此,如果以前从未分配过值,则基本上只是一种简写方式。
空合并赋值运算符是分配空合并运算符结果的一种简写方式。
官方发行说明中的一个示例:
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
Run Code Online (Sandbox Code Playgroud)