我经常看到结构是这样编码的:
if (true == a)
if (false == a)
为什么他们把常量值放在第一位而不是变量?如本例所示:
if (a == true)
if (b == true)
我经常看到结构是这样编码的:
if (true == a)
if (false == a)
为什么他们把常量值放在第一位而不是变量?如本例所示:
if (a == true)
if (b == true)
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)
fails to compile
if($a = true)
assigns the value of true
to the variable $a
and evaluates as true
The Wordpress Coding Standards mention this specifically:
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.
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.
这是一个YODA Style
编码示例
if (var a == true){
}
不如安全
if (true == var a){
}
因为当你忘记第二个=
标记时,你会得到一个无效的赋值错误,并且可以在编译时捕获它。