Is there any benefit of using null first in PHP?

后端 未结 5 1757
长发绾君心
长发绾君心 2020-12-11 15:42

Possible Duplicate:
Why do some experienced programmers write comparisons with the value before the variable?

相关标签:
5条回答
  • 2020-12-11 16:01

    It's to help you get your code right.

    If you do this, your code will work, but the effect will be a long way from what you want:

    if (self::$instance = null) {
    

    The conditional will always fail (because the = operator returns the value set, and it is falsy) but self::$instance will now be set to null. This isn't what you want.

    If you do this:

    if (null = self::$instance) {
    

    your code will fail to work, because you can't use null (or any literal such as a string or an integer) on the left-hand-side of an assignment. Only variables can be the left-hand-side of the = operator.

    So if you mistype the == as =, you get a parse error and your code completely doesn't work. This is preferable to a mystifying and hard-to-track-down bug.

    0 讨论(0)
  • 2020-12-11 16:05

    It prevents you from accidentally assigning the value to a variable, especially when only using loose type comparison (==):

    if (self::$_instance = NULL) { … } // WHOOPS!, self::$_instance is now NULL
    

    This style of conditions is often called yoda conditions. Performance wise there is no difference, both statements are equivalent.

    0 讨论(0)
  • 2020-12-11 16:06

    It's not particular to null - I've seen many coders prefer to write their expressions this way round:

    if(8 == 4 * 2) {
    

    It's just a preference which some people think is clearer.

    0 讨论(0)
  • 2020-12-11 16:17

    There's no significant performance difference. The usual benefit of writing expressions in this way is defensive programming. We want to avoid accidentally using an assignment instead of equality comparison:

    if (self::$_instance = null) { ...
    

    Woops!

    0 讨论(0)
  • 2020-12-11 16:19

    This is mainly to prevent accidental assignment:

    if (self::$_instance = null) ... //oops!
    
    0 讨论(0)
提交回复
热议问题