OR Preference changing with a return

回眸只為那壹抹淺笑 提交于 2020-05-29 08:56:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!