PHP – Difference Between (null != $object) and ($object != null)

code-qualityconditionsobject-orientedPHP

I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

Now this seems not to be the case with PHP.

Can I do something wrong in PHP when I always start with null on the left-hand side? Can I keep my behaviour from Java or do I need to train myself to do something else when dealing with PHP conditions?

Best Answer

  • There is no (technical) difference – nor is there in Java to my knowledge.
  • In PHP, do not use either of these.

I recommend you always use the strict comparison operators === and !== if possible. You will know when you actually need loose comparison operators.

Misunderstandings

I believe you may be confused about a couple of things:

  • short-circuiting operators
  • order of evaluation
  • operator precedence

I just found that the PHP manual says: "PHP checks each condition in order from left to right"

No,

  • the PHP manual does not say that, it's a comment.
  • PHP does not do that.

PHP evaluates the conditions from left to right, but it stops once the result is known:

expr1 && expr2

If expr1 evaluates to false, expr2 will not be evaluated. This is called short-circuiting and it does not seem to be very well-documented – I couldn't find any other official note on the matter except for the comment in Example #1. It is a well-known feature, though.

Fallacies

I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null


PHP checks each condition in order from left to right
Ergo: The same "best practice" can be applied

Ergo: nothing – non sequitur. The conclusion does not follow from the premise. Using constant == $variable or $variable == constant is not connected to either of short-circuiting, order of evaluation or operator precedence.

Undefined behavior

Both operands of != are always evaluated. In the case of PHP, the evaluation order (which is irrelevant here) is actually unspecified (as in absent from the documentation).