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 ?
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 ?
No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.
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
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();
//....
}