php - ?? 的运算符优先级 操作员
问题描述
我对PHP的优先级有点困惑??操作员。
https://www.php.net/manual/en/language.operators.precedence.php表示它的优先级低于 / (除)运算符。如果这是真的,$a??1/0
应该总是给出一个错误,不仅$a
是if Null
,因为它首先评估1/0
。由于它没有给出“除以零”错误,我假设??
运算符的两侧被评估为两个不同的表达式,而第二个仅在第一个产生时才被评估Null
。虽然以这种方式实现它绝对有意义,但这是否与上页所述的优先级相矛盾?
解决方案
The null coalescing ??
operator will evaluate the right part of the expression only if the left part is Null.
This means it will evaluate the left part first in order to know if it is worth evaluating the right part.
See this as an optimisation of the interpreter to prevent executing some code if it does not reach it, and it doesn't look like an operator precedence issue.
Same in an if statement, when if (expression=true), the following elseif will not be evaluated.
Referring in the link you provided in the question, consider the following when you code:
Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
The example you provide
<?php
//$a=12;
$a=Null;
echo $a??1/0;
will really be parsed as:
<?php
//$a=12;
$a=Null;
echo ($a) ?? (1/0) ;
The extra parentheses will prevent the next developer that works on your code from getting it wrong.
推荐阅读
- javascript - 如何在 android studio 中按图像 ID 添加 Searchview?
- c++ - 调试 c++ 运行时错误的好方法是什么?
- model-view-controller - 如何获取 MySQL 数据并在 CODEIGNITER 中的控制器上使用它
- android - Firebase 验证错误且不会变为真,重置后密码也不会更新
- javascript - TypeError:React__default.forwardRef 不是函数
- spotfire - 现场火分析师中的重叠日期
- javascript - CodeIgniter a.tag onclick if else 事件
- python - 如何建立自引用的多对多关系
- css - 如何在 Angular 应用程序的垫子抽屉组件中隐藏滚动条
- regex - 如果可选括号之间不存在任何内容,则不匹配