MarkPraschan
MarkPraschan

Reputation: 600

Setting a PHP variable and getting WooCommerce option at the same time?

I see the following code in WordPress and don't understand what operation is taking place:

$debug_mode = 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' );

This looks like some combination of (1) setting a variable and (2) checking if it's identical to the option set in WordPress. Can anyone spell out the logic/operators in this scenario?

Also, why might someone use this verbiage rather than just getting the option?

Upvotes: 1

Views: 122

Answers (3)

random_user_name
random_user_name

Reputation: 26150

This is what's known as a ternary.

However, due to the code style (lack of parens), it's a bit harder to see what is actually happening.

$debug_mode = 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' );

My preference is to wrap the condition in parens, to make it a bit more obvious:

$debug_mode = ( 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' ) );

Which now looks more clearly like what it is - an assignment to the variable $debug_mode of whether or not the woocommerce_shipping_debug_mode option is === to yes (which will return either a TRUE or FALSE.

The "long hand" of what this would look like is this:

$debug_mode = ( 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' ) ) ? TRUE : FALSE;

But, since the condition returns TRUE or FALSE anyway, the ? TRUE : FALSE portion is redundant.

To explicitly answer your second question, "why would someone use this verbiage", - they are just getting the option value - they wrote it this way because it's brief. This is a perfect example of why we should write code for humans, not just for machines :)

Upvotes: 2

Borisu
Borisu

Reputation: 848

You're not getting the option in this case, rather assigning the result of the check to the debug_mode. The logical operation === will take precedence to the assignment, so evaluating half way returns

$debug = true;  // if the get_option is set to 'yes'

and

$debug = false; // otherwise

Upvotes: 1

Serhii Andriichuk
Serhii Andriichuk

Reputation: 988

You may have many environments (production, testing, development) and for each you can have its custom option for woocommerce_shipping_debug_mode key and you don't want to display debug info on production site. Also this key may not exist, that's why you check option with default value

Upvotes: 0

Related Questions