'string' == $var 或 $var == 'string' 区别?
'string' == $var or $var == 'string' difference?
我在看一段代码,看到代码作者使用了下面的if语句
if ( 'string' == $var )
我经常使用的地方
if ( $var == 'string' )
我想知道的是,除了style/looks之外,它是否还有其他功能。将 $var 与 'string' quicker/slower 进行比较,而不是将 'string' 与 $var 进行比较?
Why if( constant == variable ) is preferred instead of if ( variable == constant )
这是对您问题的回答。
如果您错过等号,这有助于调试。
Because that form makes it harder to introduce a bug by forgetting one
of the equals signs. Imagine if you did this:
if (k = 5) This was intended as a comparison, but it's now an
assignment! What's worse, it is legal, and it will mess up your
program in multiple ways (the value of k is changed, and the
conditional always evaluates to true).
Contrast this with
if (5 = k) This is not legal (you cannot assign to a literal) so the
compiler will immediately flag it as an error.
用评论中Hanky 웃 Panky的话来说:
They are both equivalent but 'string'==$var is a better approach
because it helps in debugging if you miss an equal sign.
我在看一段代码,看到代码作者使用了下面的if语句
if ( 'string' == $var )
我经常使用的地方
if ( $var == 'string' )
我想知道的是,除了style/looks之外,它是否还有其他功能。将 $var 与 'string' quicker/slower 进行比较,而不是将 'string' 与 $var 进行比较?
Why if( constant == variable ) is preferred instead of if ( variable == constant )
这是对您问题的回答。 如果您错过等号,这有助于调试。
Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:
if (k = 5) This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).
Contrast this with
if (5 = k) This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.
用评论中Hanky 웃 Panky的话来说:
They are both equivalent but 'string'==$var is a better approach because it helps in debugging if you miss an equal sign.