In WordPress’ core code, you often see this:
if (1 == $someVar)
as opposed to this:
if ($someVar == 1)
I don’t know if the first way is a WordPress-centric style of coding, but I’ve only noticed it in WP code (either core or 3rd-party code).
In WordPress’ core code, you often see this:
if (1 == $someVar)
as opposed to this:
if ($someVar == 1)
I don’t know if the first way is a WordPress-centric style of coding, but I’ve only noticed it in WP code (either core or 3rd-party code).
You must be logged in to post a comment.
This coding style is known as a Yoda Condition, and it’s nothing specific to WordPress. I’ve used the same style in C++, C#, and even JavaScript code.
The main benefit of a Yoda Condition is that it prevents accidental value assignment from a typo. Consider the following (often-seen-in-the-wild) typo:
This will always evaluate to
true
, but has the additional consequence of assigning the value1
to$some_variable
. Sometimes this is intentional, though. In WordPress specifically, you’ll often see things like:The point of this code is to assign a new value to the
$post
variable, and it works because thesome_function()
being used will returnfalse
on error.Yoda Conditions (reversing the order of the
==
equality operator) protect you from accidentally assigning values when you didn’t mean to. If you make a mistake and only put one=
in the code, you’ll get an error because you can’t assign to a regular value:Like I said, this is not unique to WordPress, or even to PHP, however it is part of the required WordPress coding standards. If you’re writing a plugin or theme for general distribution, or contributing to core, you need to know both what Yoda Conditions are and how to use them