本文介绍了是否有“空安全运算符"?在 PHP 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用某种安全导航操作符来编写以下语句?
echo $data->getMyObject() != null ? $data->getMyObject()->getName() : '';
所以它看起来像这样:
echo $data->getMyObject()?->getName();
推荐答案
从 PHP 8 开始,您可以使用 空安全运算符 结合空合并运算符允许您编写如下代码:
From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like:
echo $data->getMyObject()?->getName() ?? '';
通过使用 ?->
而不是 ->
运算符链被终止,结果将为空.
By using ?->
instead of ->
the chain of operators is terminated and the result will be null.
查看对象内部"的运算符被视为链条的一部分.
The operators that "look inside an object" are considered part of the chain.
- 数组访问 ([])
- 属性访问权限 (->)
- 空安全属性访问 (?->)
- 静态属性访问 (::)
- 方法调用 (->)
- 空安全方法调用 (?->)
- 静态方法调用 (::)
例如代码:
$string = $data?->getObject()->getName() . " after";
如果 $data 为 null,则该代码等效于:
if $data is null, that code would be equivalent to:
$string = null . " after";
由于字符串连接运算符不是链"的一部分,因此不会短路.
As the string concatenation operator is not part of the 'chain' and so isn't short-circuited.
这篇关于是否有“空安全运算符"?在 PHP 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!