最后一个操作数为空的空合并运算符

Null Coalesce Operator with a null last operand

它工作正常,不会引起问题

echo $formErrorBag[ 'email' ] ?? null

但这是公认的做法吗?从未见过与 null.

一起使用的示例

这是完全合法的,并且被接受。如果 $formErrorBag 没有 'email' 键,这是避免引发 E_NOTICE 的一种非常简单和优雅的方法。

空合并运算符使用 isset() 检查值,因此:

echo $formErrorBag['email'] ?? null;

等于:

if(isset($formErrorBag['email'])){
  echo $formErrorBag['email'];
} else {
  echo null;
}

我真的不明白这有什么意义,因为您仍在执行一个实际上什么都不做的函数。如果您这样做是为了避免引发 E_NOTICE,您可以简单地使用 error_reporting() 将其关闭,因为您的方法有点破坏了这一点。

它是为了警告您代码中可能存在的错误,而不是寻找抑制它的技术。

error_reporting(error_reporting() ^ E_NOTICE); // turn notices off keep remaining flags intact.

echo $array['doesnotexist'];
echo $array['etc'];

error_reporting(error_reporting() | E_NOTICE); // turn it back on.