29

否定演算子は代入演算子よりも優先順位が高くなりますが、式で低いのはなぜですか?

例えば

if (!$var = getVar()) {

前の式では、割り当てが最初に発生し、否定が後で発生します。否定を最初に、次に割り当てを行うべきではありませんか?

4

3 に答える 3

47

の左側= はである必要がありvariableます。$varはですが、そうvariable!$varはありません(expr_without_variableです)。

したがって、PHPは、可能な唯一の方法、つまり。として式を解析し!($var = getVar())ます。優先順位がここで発揮されることはありません。

の優先順位=が関連する例は次のとおりです。

$a = $b || $c // ==> $a = ($b || $c), because || has higher precedence than =
$a = $b or $c // ==> ($a = $b) or $c, because or has lower precedence than =
于 2013-02-28T20:03:17.510 に答える
4

In short, assignments will always have precedence over their left part (as it would result in a parse error in the contrary case).

 <?php
 $b=12 + $a = 5 + 6;
 echo "$a $b\n";
 --> 11 23

 $b=(12 + $a) = (5 + 6);
 echo "$a $b\n";
 --> Parse error

The PHP documentation has now a note concerning this question: http://php.net/manual/en/language.operators.precedence.php (i guessed it was added after your question)

Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a

于 2015-09-22T08:38:33.033 に答える
0

Negotiation operator needs to check a single value at the next, so if you give like this

!$var = getVar()

the operator onlyapplicable for the next variable so !$var is will seperated. so only we need to give

!($var = getVar())

于 2015-09-24T06:33:04.843 に答える