PHP variable assignment needs parentheses -


i wrote code , found didn't work expected.

for example, following return false or throw exception, undefined variable: a:

if ($a = 12 && $a == 12) {     return true; } else {     return false; } 

i fixed wrapping assignment in parentheses:

if (($a = 12) && $a == 12) {     return true; } else {     return false; } 

it lucky guess. i'm wondering why parentheses needed , haven't found explains why.

that because of operator precedence. assignment operator = has lower precedence &&, without parenthesis doing following.

if ($a = (12 && $a == 12)) 

observe second $a not yet defined before assignment happens, because has evaluated before assignment can happen.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

javascript - Which segment of a polyline was clicked? -

c# - Avoiding duplicate methods for Task and Task<T> -