PHP中的优先运算符'OR'和'=' [英] Precedence operator 'OR' and '=' in PHP

查看:123
本文介绍了PHP中的优先运算符'OR'和'='的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$a = 1;
$a OR $a = 'somthing'
echo $a; //1

为什么?如果=的优先级较高,则使用"OR",然后为什么要先执行OR?

Why? If = have much precedence then 'OR' then why OR execute first?

推荐答案

因为OR的优先级高于

$a OR $a = 'somthing'

将被解析为:

($a OR $a) = 'somthing'

从技术上讲,这是错误的,因为您不能分配给表达式(而程序员希望像编写代码那样编写表达式,因此它应该是有效的表达式).

that would be technically wrong because you can't assign to an expression (while programmers would like to write expression like this is coding so it should be a valid expression).

因为or运算符的优先级较低,因此表达式$a OR $a = 'somthing'都被定义为$a OR ($a = 'somthing'),并且根据短路,将$a的第一个操作数评估为true,未评估第二个操作数表达式,并且c6>保留为1.

because precedence of or operator was low hence the expression $a OR $a = 'somthing' pareses as $a OR ($a = 'somthing') And according to short-circuit first operand that is $a was evaluated as true and second operand expression not evaluated and a remains 1.

记住优先级规则可得出语法规则,从而告诉您如何解析表达式.但是优先级是一个编译时属性,它告诉我们表达式的结构.评估是一种运行时行为,它告诉我们如何计算表达式(因此,如何通过优先级无法完全确定表达式的计算方式).和PHP文档似乎说的是相同的:

Remember precedence rules derives grammar rules and hence tells how expression will be parse. But precedence is a compile-time property that tells us how expressions are structured. Evaluation is a run-time behavior that tells us how expressions are computed (hence how expressions will be evaluates can't completely determine by precedence). And PHP docs seems to say same:

运算符优先级
运算符的优先级和关联性仅决定表达式的方式 分组,它们没有指定评估顺序. PHP不 (通常)指定表达式的顺序 被评估的代码和假定特定评估顺序的代码应 避免使用,因为行为可能会在PHP版本或 取决于周围的代码.

Operator Precedence
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

这篇关于PHP中的优先运算符'OR'和'='的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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