2

When reading Symfony2 code I came across this comparaison many times

if (null === $variable ) { ... }

I use

if ($variable === null ){ ... }

because I see it more readable.

Is there a wisdom behind using the first notation ?

zizoujab
  • 7,603
  • 8
  • 41
  • 72
  • This question pops up from time to time, the older Q&A material we have on site is normally giving better directions as the quickly types answers nowadays: [Why does one often see “null != variable” instead of “variable != null” in C#?](http://stackoverflow.com/q/271561/367456) (Nov 2008) - [Why do some experienced programmers write expressions this way? \[duplicate\]](http://stackoverflow.com/q/3309089/367456) (Jul 2010) - [Is there any benefit of using null first in PHP?](http://stackoverflow.com/q/7261117/367456) (Aug 2011) – hakre May 04 '14 at 09:39

3 Answers3

6

No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.

Conditions, Yoda

4

It helps prevent accidental assignments:

if ($foo = null) { ... }

would not cause a parse error, while will

if (null = $foo) { ... }

1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10 2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd

Eldarni
  • 425
  • 1
  • 3
  • 9
  • 1
    I wonder why this was downvoted. – Felix Kling Mar 08 '14 at 17:40
  • 1
    I don't wonder why this was downvoted. -- linked demos are not working nor is given any info what they should stand for (and to allow me some personal taste: crappy code-pad site that is linked there) – hakre May 04 '14 at 09:21
1

Not only does it help prevent accidental assignments, but also avoids confusion when we do intentionally want to make an assignment when evaluating a condition.

if (null !== $article = $repository->findOneById($request->query->get('id'))) {
    $title = $article->getTitle();

    //....
}
Adam Elsodaney
  • 7,722
  • 6
  • 39
  • 65