运算符“或"的优先级高于“或".和分配 [英] Operators precedence of "or" and assignment

查看:130
本文介绍了运算符“或"的优先级高于“或".和分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天发现了一些有趣的代码片段.简化后,它看起来像这样:

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 expression if x then y else false; the expression x Sor y is equivalent to if 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆