PHP - reversed order in if statement

前端 未结 7 1203
-上瘾入骨i
-上瘾入骨i 2021-01-12 01:19

This is a question that is bugging me for a long time and can\'t find any answer... Noticed it\'s used quite a lot by Zend Framework Developers,

What is the differen

7条回答
  •  礼貌的吻别
    2021-01-12 01:46

    It is a good practice for writing if statement. Consider this code:

    if (10 == $var) {
      echo 'true';
    } else {
      echo 'false';
    }
    

    If you forgot one equal sign:

    if (10 = $var) { }
    

    Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:

    if ($var = 10) { }
    

    will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.

提交回复
热议问题