Setting default values (conditional assignment)

后端 未结 5 1786
一生所求
一生所求 2020-12-05 17:26

In Ruby you can easily set a default value for a variable

x ||= \"default\"

The above statement will set the value of x to \"default\" if

相关标签:
5条回答
  • 2020-12-05 18:00
    isset($x) or $x = 'default';
    
    0 讨论(0)
  • 2020-12-05 18:02

    As of PHP 7.0, you can also use the null coalesce operator

    // PHP version < 7.0, using a standard ternary
    $x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';
    // PHP version >= 7.0
    $x = $_GET['y'] ?? 'not set';
    
    0 讨论(0)
  • 2020-12-05 18:09

    I wrap it in a function:

    function default($value, $default) {
        return $value ? $value : $default;
    }
    // then use it like:
    $x=default($x, 'default');
    

    Some people may not like it, but it keeps your code cleaner if you're doing a crazy function call.

    0 讨论(0)
  • 2020-12-05 18:12

    As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

    $x = $x ?: 'default';
    
    0 讨论(0)
  • 2020-12-05 18:15

    I think your longer form is already the shortcut for php... and I wouldn't use it, because it is not good to read

    Some notice: In the symfony framework most of the "get"-Methods have a second parameter to define a default value...

    0 讨论(0)
提交回复
热议问题