问题
From what I see operator precedence makes sense in these two examples:
$a = false;
$b = true;
$c = $a || $b;
Here $c is true
$a = false;
$b = true;
$c = $a or $b;
Here $c is false
I understand the reasoning behind it. However the following:
$a = false;
$b = true;
return $a or $b;
Returns true, which puzzles me.
What is the reason for this?
回答1:
or
has lower precedence than =
, so this:
$c = $a or $b;
Becomes this:
($c = $a) or $b;
But this doesn't make sense:
(return $a) or $b;
So you get this:
return ($a or $b);
回答2:
Within an expression, operator precedence applies. =
, ||
and or
are all operators and $c = $a or $b
is an expression. And according to operator precedence it evaluates as ($c = $a) or $b
.
However, return
is a statement. return
is not an operator and does not group by operator precedence. It always evaluates as return <expression>
, and therefore always as return ($a or $b)
.
The result of the expression $c = $a or $b
is true
BTW. $c
is being assigned false
in the course of the expression, but the expression overall returns the value true
($b
). So even this would return true
:
return $c = $a or $b;
来源:https://stackoverflow.com/questions/51520435/or-preference-changing-with-a-return