首页 > 解决方案 > ?? 的运算符优先级 操作员

问题描述

我对PHP的优先级有点困惑??操作员。

https://www.php.net/manual/en/language.operators.precedence.php表示它的优先级低于 / (除)运算符。如果这是真的,$a??1/0应该总是给出一个错误,不仅$a是if Null,因为它首先评估1/0。由于它没有给出“除以零”错误,我假设??运算符的两侧被评估为两个不同的表达式,而第二个仅在第一个产生时才被评估Null。虽然以这种方式实现它绝对有意义,但这是否与上页所述的优先级相矛盾?

标签: php

解决方案


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.


推荐阅读