The negation operator has higher precedence than the assignment operator, why is it lower in an expression?
e.g.
if (!$var = getVar()) {
In the previous expression the assignment happens first, the negation later. Shouldn't the negation be first, then the assignment?
The left hand side of =
has to be a variable
. $var
is a variable
, whereas !$var
is not (it's an expr_without_variable
).
Thus PHP parses the expression in the only possible way, namely as !($var = getVar())
. Precedence never comes to play here.
An example of where the the precedence of =
is relevant is this:
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With