否定演算子は代入演算子よりも優先順位が高くなりますが、式で低いのはなぜですか?
例えば
if (!$var = getVar()) {
前の式では、割り当てが最初に発生し、否定が後で発生します。否定を最初に、次に割り当てを行うべきではありませんか?
否定演算子は代入演算子よりも優先順位が高くなりますが、式で低いのはなぜですか?
例えば
if (!$var = getVar()) {
前の式では、割り当てが最初に発生し、否定が後で発生します。否定を最初に、次に割り当てを行うべきではありませんか?
の左側=
はである必要があり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 =
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
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())