PHP Question

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 )

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.)

Answer Source

There's an explanation on the WordPress site:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download