Possible Duplicate:
Why do some experienced programmers write comparisons with the value before the variable?
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.
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.
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.
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!
This is mainly to prevent accidental assignment:
if (self::$_instance = null) ... //oops!