1

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?

MarkPraschan
  • 560
  • 6
  • 8

3 Answers3

2

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

random_user_name
  • 25,694
  • 7
  • 76
  • 115
1

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
Djave
  • 8,595
  • 8
  • 70
  • 124
Borisu
  • 828
  • 7
  • 15
0

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

  • That makes sense, but if the key didn't exist, wouldn't get_option return false, making $debug_mode = false because 'yes' is not identical to false? Is the default redundant here? – MarkPraschan Nov 27 '18 at 14:11
  • 1
    It is just to show default value and string comparisons for quick check – Serhii Andriichuk Nov 27 '18 at 14:35