Why do WordPress code consistently have the uncommon “boolean literal === some dynamic expression” order of comparison parts?

I find that WordPress code always have this way of coding:

if ( false === ( $value = get_transient( 'value' ) ) ) {
     // this code runs when there is no valid transient set
}

I’d expect it to be something like if ( ( $value = get_transient( 'value' ) ) === false ).

Read More

Have the WordPress developers mentioned any reason for using this PHP syntax? There should be a reference to this somewhere, but this syntax is difficult to google.

(I don’t feel that this belongs in the WordPress site, as it’s more related to PHP syntax.)

Related posts

2 comments

  1. There’s an explanation on the WordPress site:

    https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions

    It’s called Yoda conditions; in short, it’s because it’s very easy for someone to mix up the assignment operator in PHP with the equality operator, so given a line of code:

    if (x = true) 
    

    is almost certainly a typo, but won’t generate any errors, because it’s valid syntax.

    On the other hand:

    if (true = x) {
    

    means that you’re trying to assign the value of x to the constant true, and PHP will see that and generate an error message.

    So it’s an easy way to avoid some of the subtle syntax issues that PHP lets you get away with.

  2. It’s pretty usual in C.
    People use it to avoid accidental variable attribution as for example:

    if ($a == 5);
    // Works as intended
    if ($a = 5);
    // Sets $a to 5
    
    
    if (5 == $a);
    // Works as intended
    
    if (5 == $a);
    // Compile Error
    

    People Call it: Yoda Conditions

Comments are closed.