THE PENDING DRAFT

Yoda Conditions

April 25, 2015

Have you ever heard of Yoda Conditions? Maybe you saw some code written like this:

if ( true == $the_force ) {
    $victorious = you_will( $be );
}

I never really got why it could be useful to write a condition in that order until i found this part of the WordPress’s PHP Coding Standards:

In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.

Now that makes a whole lot of sense, so make sure to write your conditions in that order from now on, even if it sounds strange at first. Or, as it is appropriately stated in the Coding Standards:

A little bizarre, it is, to read. Get used to it, you will.

PHP Coding Standards – Yoda Conditions

Leave your comment