What's the rationale behind “Assignment in con

2019-07-06 04:01发布

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.?

5条回答
一夜七次
2楼-- · 2019-07-06 04:42

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.

查看更多
淡お忘
3楼-- · 2019-07-06 04:42

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))
{
    /* ... */
}
查看更多
冷血范
4楼-- · 2019-07-06 04:50

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.

查看更多
男人必须洒脱
5楼-- · 2019-07-06 04:54

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.

查看更多
趁早两清
6楼-- · 2019-07-06 04:58

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) {
    // ...
}
查看更多
登录 后发表回答