运算符“或"的优先级高于“或".和分配 [英] Operators precedence of "or" and assignment
问题描述
今天发现了一些有趣的代码片段.简化后,它看起来像这样:
Found some interesting code snippet today. Simplified, it looks like this:
$var = null;
$var or $var = '123';
$var or $var = '312';
var_dump($var);
问题是,据我所知,分配的优先级更高OR
,因此,正如我假设的那样,var_dump
应该输出312
(第一个-分配,第二个-逻辑比较).但是结果是不同的,我得到了123
(首先-检查$var
是否转换为true
,第二-检查不是,则赋值).
The thing is that, as i know, precedence of assignment is higher that OR
, so, as i assume, var_dump
should output 312
(first - assign, second - compare logically). But result is defferent, i getting 123
(first - check if $var
converting to true
, second - if not, assign value).
问题是它如何工作?
为什么or
和||
的行为相同?
推荐答案
短路表达式
x Sand y
(使用Sand表示短路品种)等效于条件表达式if x then y else false;
表达式x Sor y
等效于if x then true else y
.
The short-circuit expression
x Sand y
(using Sand to denote the short-circuit variety) is equivalent to the conditional expressionif x then y else false;
the expressionx Sor y
is equivalent toif x then true else y
.
在php中.
return x() and y();
等于
if (x())
return (bool)y();
else
return false;
return x() or y();
等于
if (x())
return true;
else
return (bool)y();
所以,交易不只是优先.
So, deal is not just in precedence.
这篇关于运算符“或"的优先级高于“或".和分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!