What's the rationale behind “Assignment in condition” warnings in Zend Studio IDE?

允我心安 提交于 2019-12-23 15:54:00

问题


Given:

if ($variable = get_variable('variable')) {
    // ...
}

The *$variable = get_variable('variable')* throws an 'Assignment in condition' warning in Zend Studio. I understand what the warning means, but does anyone know what the rationale behind it is? Is it merely coding conventions, a matter of readability, etc.?


回答1:


This is a very common warning issued by IDEs/compilers in most languages that allow this construct: since = (assignment) and == (comparison) are very similar, and comparison is more common within an if statement, the warning is just there to let you know that you may have put in an assignment by mistake where you really intended a comparison.




回答2:


It does this because:

if ($variable = get_variable('variable')) {
    // ...
}

is very close to:

if ($variable == get_variable('variable')) {
    // ...
}

The former is not exactly a good practice to get into. Zend Studio assumes that you are more likely to have meant the latter case, so it warns you about this. Not to say that this isn't a useful tool. It is usually more acceptable in a while loop, for reading a file line by line (while there is still a line to read). The problem is that it is hard to quickly pick out.




回答3:


I believe it's mainly there because people normally forget the double equals. This should get rid of the warning:

if ($variable = get_variable('variable') != false) {
    // ...
}



回答4:


Because often its just a typo, if you forgot one "="

if ($a = $b) { /* $a and $b equal? */ }

So the IDE advise you to have a look at it.




回答5:


It's very very common mistake to write assignment operator = instead of equality check ==.

In all cases I know you can get rid of that warning by wrapping the assignment in parenthesis like this.

if (($var = 1))
{
    /* ... */
}


来源:https://stackoverflow.com/questions/4250388/whats-the-rationale-behind-assignment-in-condition-warnings-in-zend-studio-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!