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.)
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:
is almost certainly a typo, but won’t generate any errors, because it’s valid syntax.
On the other hand:
means that you’re trying to assign the value of
x
to the constanttrue
, 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.
It’s pretty usual in C.
People use it to avoid accidental variable attribution as for example:
People Call it: Yoda Conditions