可能重复: php处于错误状态的地方
Possible Duplicate: php false place in condition
我注意到很多PHP代码使用条件语句,例如CONST == VARIABLE.我长大后总是总是以相反的方式表达语法.有这种结构的原因吗?
I have noticed that a lot of PHP code uses conditional statements like CONST == VARIABLE. I grew up with the syntax always articulated in reverse. Is there a reason for this structure?
示例:
// this is the way I see it most typically represented in PHP if ( false == $foobar ) { // do this } // this is the way I normally do it if ( $foobar == false ) { // do this }推荐答案
这是为了防止==和=之间的常见拼写错误,即所谓的yoda条件.请考虑以下内容:
This is to prevent a common typo between == and =, known as a yoda condition. Consider the following:
if( false = $foobar) {这将导致错误,并捕获可能被视为错误的错误,因为您无法为false分配任何内容.相反:
This would result in an error, catching what would be considered a bug, since you cannot assign anything to false. On the contrary:
if( $foobar = false) {这是有效的语法,很容易犯错.
This is valid syntax, and is quite an easy mistake to make.
但是,我通常更喜欢if( $foobar == false)语法,因为单元测试应该能够捕获这些程序错误.
However, I typically prefer the if( $foobar == false) syntax, as unit tests should be able to catch these programmatic mistakes.
更多推荐
条件语句中的顺序
发布评论