PHP - reversed order in if statement

前端 未结 7 1195
-上瘾入骨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:34

    If you accidentally write:

    if (null = $this->user) { ... }   
    

    you will get a syntax error.

    If you accidentally write:

    if ($this->user = null) { ... }
    

    you will be searching for a reason of strange behavior of your application for a long time.

    0 讨论(0)
  • 2021-01-12 01:45

    These are called yoda conditions.

    The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.

    Also, what mishu said :)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 01:52

    This is not a difference for the way your script works, it's just a coding standard, a recommendation

    The reason why it is recommended to use it this way:

    if (null == $this->user)
    

    is the fact that if you mistype and write = instead of == you will get an error, while

    ($this->user = null)
    

    instead of

    ($this->user == null)
    

    works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)

    and I guess it just extended as a habit to the strict comparison operator (===)

    Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.

    0 讨论(0)
  • 2021-01-12 01:57

    The result will be the same, however, the second is logical. You want to check if the variable is NULL, not if NULL is the variable... The reason for doing it the other way around is described here: http://umumble.com/blogs/Programming/321/

    0 讨论(0)
  • 2021-01-12 02:00

    There is no difference in order when comparing values.

    It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.

    0 讨论(0)
提交回复
热议问题