条件语句中的顺序 [英] Order in conditional statements

查看:107
本文介绍了条件语句中的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
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.

这篇关于条件语句中的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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