PHP If Shorthand Best Practce

217 views Asked by At

Just a weird PHP question about best practice. Assuming the following function:

function get_option($val) {
  return false;
}

I want to assign to a $locale variable, the value returned from this function and, if false, set to a default en_GB one. I discovered 2 option for achieving this goal:

1st Option:
$locale = ( $locale = get_option( 'language_code' ) ) ? $locale : 'en_GB';

2nd Option:
$locale = get_option( 'language_code' ) ? get_option( 'language_code' ) : 'en_GB';

I would like to know which one is more correct and why.

Thanks

3

There are 3 answers

4
Karoly Horvath On BEST ANSWER

Both seem a bit verbose to me, to avoid duplicated calculations, I would prefer the first one (perhaps splitted to 2 lines of code).

You can create a helper function, this one has false hardcoded, but you could even pass it as a parameter:

function use_default_false($var, $default) {
    return ($var !== false) ? $var : $default;
}

Then your code becomes:

$locale = use_default_false(get_option('language_code'), 'GB');

Since PHP5.3 you can use the shorthand ternary operator ?:.

Be aware that it will check the left-hand side argument for truthy, which prevents it to be used if the valid value you're checking evaluates to false (e.g.: 0, "", "0", array()...). Because of that, I wouldn't generally recommend it, but in this case I assume the locale is a non-empty non-"0" string, so it should be fine.

$locale = get_option('language_code') ?: 'GB';

With PHP7 you can use the null coalesce operator ??.

It checks for NULL so you have to alter the default value returned by your function.

$locale = get_option('language_code') ?? 'GB';
7
AvikB On

I would prefer the second one

basically if get_option( 'language_code' ) returns true then get_option( 'language_code' ) execute else other option.

it is easier to understand, and maintainable.

for duplicate code issue use something similer to this:

you need to post some more code, but here is a better way to do it:

var var1 = null;
function get_option( somevar ){
if (var1  != null) {
            return true;
        } else {
              var1  = do some stuff;
              return true;
        }
}

and then call the function like this

$locale = get_option( 'language_code' ) ? var1 : 'en_GB';
0
aross On

The second option is better, but even better would be to use a shorthand ternary

$locale = get_option('language_code') ?: 'en_GB';

If your function returns only locale strings or false, this is the correct solution (and it doesn't require PHP7).

However, as mentioned in the comments, it might be an idea to return default values directly from the get_option function for a more architecturally sound solution. That means the caller is not made responsible for setting the default. Just read that you're using Wordpress and have no control over the inner workings of the function, but the advice in general still stands