为什么在if条件中为常量 [英] Why Constant first in an if condition
问题描述
我经常看到结构是否像这样编码:
I often see if structures being coded like this:
if (true == a)
if (false == a)
为什么他们先将常数值放在首位而不是变量?如下例所示:
Why do they put the constant value first and not the variable? as in this example:
if (a == true)
if (b == true)
推荐答案
这称为yoda语法或yoda条件。
This is called yoda syntax or yoda conditions.
它用于帮助防止意外分配。
It is used to help prevent accidental assignments.
如果你忘记了等号,它将会失败
If you forget an equals sign it will fail
if(false = $ a)
无法编译
if($ a = true)
将 true
的值分配给变量 $ a
并评估为 true
if($a = true)
assigns the value of true
to the variable $a
and evaluates as true
Wordpress编码标准具体提到这一点:
if ( true == $the_force ) {
$victorious = you_will( $be );
}
进行逻辑比较时,始终放置变量在左边的
侧,常数或文字。
When doing logical comparisons, always put the variable on the right side, constants or literals on the left.
在上面的例子中,如果省略等号(承认它,它会发生
甚至对我们经验最丰富的人来说),你会得到一个解析错误,因为
你不能分配给一个像true一样的常量。如果声明是
其他方式($ the_force = true),则赋值将是
完全有效,返回1,导致if语句计算为
true,你可能是追逐那个bug一段时间。
In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.
有点奇怪,是的。习惯了,你会的。
A little bizarre, it is, to read. Get used to it, you will.
这篇关于为什么在if条件中为常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!