PHP 8 中介绍的空合并运算符 (??) 和空安全运算符 (?->) 之间的区别

Difference Between null coalescing operator (??) and nullsafe operator (?->) introduced in PHP 8

我可以在 PHP 中使用 ?? 运算符来处理未定义的数组索引。 如果 null 安全运算符为我提供相同或扩展 ?? 运算符的功能,我感到困惑?

编辑:

我可以在现有的 PHP 版本中检查数组中是否定义了特定的 属性:

$user_actions = ['work' => 'SEO','play' => 'Chess', 'drink' => 'coffee'];
$fourth_tag = $user_tags['eat'] ?? "n/a";

我想了解 null 安全运算符是否为我提供了更好的方法?

空合并运算符 (??) 作为一个 if 语句工作,如果第一个为空,则取两个值,然后将其替换为第二个。

$a = null;
$b = $a ?? 'B';

此处 $b 将得到值 B 因为 $anull;

在 PHP8 中,引入了 NullSafe 运算符 (?->) 将提供将调用从一个函数链接到另一个函数的选项。根据此处的文档:(https://www.php.net/releases/8.0/en.php#nullsafe-operator)

Instead of null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.

这是文档中的示例:


$country =  null;

if ($session !== null) {
  $user = $session->user;

  if ($user !== null) {
    $address = $user->getAddress();
 
    if ($address !== null) {
      $country = $address->country;
    }
  }
}

但是在 PHP8 中你可以简单地这样做:


$country = $session?->user?->getAddress()?->country;

所以这两个操作员的工作方式有很大不同。