Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does negation happen last in an assignment expression in PHP?

Tags:

php

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?

like image 957
goyote Avatar asked Sep 17 '12 06:09

goyote


2 Answers

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 =
like image 110
NikiC Avatar answered Nov 13 '22 03:11

NikiC


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

like image 4
Adam Avatar answered Nov 13 '22 04:11

Adam