PHP中的安全导航操作符?

时间:2012-09-10 12:28:17

标签: php

有没有办法使用某种safe navigation operator编写以下语句?

echo $data->getMyObject() != null ? $data->getMyObject()->getName() : '';

所以它看起来像这样:

echo $data->getMyObject()?->getName();

4 个答案:

答案 0 :(得分:13)

从PHP 8开始,您可以使用null safe operator并将其与null合并运算符结合使用,从而可以编写如下代码:

geo-types

通过使用geo-types而非echo $data->getMyObject()?->getName() ?? ''; 终止运算符链,结果将为空。

“在对象内部看”的运算符被视为链的一部分。

  • 数组访问([])
  • 财产访问权(->)
  • Nullsafe属性访问(?->)
  • 静态属性访问(::)
  • 方法调用(->)
  • Nullsafe方法调用(?->)
  • 静态方法调用(::)

例如代码:

?->

如果$ data为null,则该代码等效于:

->

由于字符串串联运算符不是“链”的一部分,因此也不会短路。

答案 1 :(得分:8)

没有。

处理这个问题的绝对最佳方法是设计对象,使它们始终返回特定类型的已知,良好,定义的值。

对于绝对不可能的情况,你必须这样做:

$foo = $data->getMyObject();
if ($foo) {
    echo $foo->getName();
}

或者

echo ($foo = $data->getMyObject()) ? $foo->getName() : null;

答案 2 :(得分:0)

Nullsafe运算符使您可以链接调用,而不必检查链接的每个部分是否都不为空(空变量的方法或属性)。

PHP 8.0

$city = $user?->getAddress()?->city

PHP 8.0之前的版本

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

使用null coalescing operator(不适用于方法):

$city = null;
if($user !== null) {
    $city = $user->getAddress()->city ?? null;
}

Nullsafe operator抑制错误:

警告:在致命错误中尝试读取null上的属性“ city”:

未捕获的错误:调用成员函数getAddress()为空

但是它不适用于数组键:

$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null

$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"

答案 3 :(得分:-1)

我通常使用isset运算符检查null属性。

if (!isset($array['with']['a']['big']['nest'])) {
    return;
}

// now i'm safe to access.

https://www.php.net/manual/pt_BR/function.isset.php

相关问题