Best way to give a variable a default value (simulate Perl ||, ||= )

后端 未结 8 1359
眼角桃花
眼角桃花 2020-12-07 11:46

I love doing this sort of thing in Perl: $foo = $bar || $baz to assign $baz to $foo if $bar is empty or undefined. You al

相关标签:
8条回答
  • 2020-12-07 12:15

    I think in general doing something like this:

    $foo = $bar || $baz;
    

    is a bad idea, unless $bar and $baz are both booleans. If they arent:

    $bar = 10;
    $baz = 11;
    

    then the question becomes: what determines if something is true or false? Most people would probably expect zero to be false, and everything else to be true. But with some languages (for example Ruby), only false and nil are false, which means both 0 and 1 would be true. Because of this cross language ambiguity, I think it best to be explicit in these cases:

    if ($bar !== 0) {
       $foo = $bar;
    } else {
       $foo = $baz;
    }
    

    or:

    $foo = $bar !== 0 ? $bar : $baz;
    
    0 讨论(0)
  • 2020-12-07 12:16

    In PHP earlier than 7.*, one may use ?: for an undefined variable having errors locally suppressed with an @:

    $foo = @$bar ?: $baz;
    
    0 讨论(0)
  • 2020-12-07 12:22

    A common idiom to stay compatible with older PHP versions is:

     $var = $bool   or   $var = "default";
     // If I use it, then only with excessive spaces for clarity.
    

    This works for values that can be evaluated in boolean context. The advantage here is that it also gives you said debug e_notice should the variable be undefined.

    0 讨论(0)
  • 2020-12-07 12:35

    Thanks for all the great answers!

    For anyone else coming here for a possible alternative, here are some functions that help take the tedium out of this sort of thing.

    function set_if_defined(&$var, $test){
        if (isset($test)){
            $var = $test;
            return true;
        } else {
            return false;
        }
    }
    
    function set_unless_defined(&$var, $default_var){
        if (! isset($var)){
            $var = $default_var;
            return true;
        } else {
            return false;
        }
    }
    
    function select_defined(){
        $l = func_num_args();
        $a = func_get_args();
        for ($i=0; $i<$l; $i++){
            if ($a[$i]) return $a[$i];
        }
    }
    

    Examples:

    // $foo ||= $bar;
    set_unless_defined($foo, $bar);
    
    //$foo = $baz || $bletch
    $foo = select_defined($baz, $bletch);
    

    I'm sure these can be improved upon.

    0 讨论(0)
  • 2020-12-07 12:35

    A possible solution: defaultFor( )

    Unless we have a factory solution (which is indeed very annoying), I'd recommend the following little helper. It does the job in most cases:

    
        function defaultFor(&$x,$default=null) {
            if(!isset($x)) $x = $default;
        }
    
        //--------------------  Now you can do this: --------------
    
        defaultFor($a,"Jack");  // if $a is not set, it will be "Jack"
        defaultFor($x);         // no more notices for $x but keep it !isset
    
    

    I hope this is close to what you wanted to achieve. It will not give you any notices if you use it with a nonexistent variable, and it's quite convenient. Surely it has a drawback: the default value always gets calculated beforehand so don't use it with anything heavy as a second parameter, like a file_get_contents or something. In those cases, you're better off with isseting.

    0 讨论(0)
  • 2020-12-07 12:36

    this is another good format for the isset case

    isset($foo) || $foo= $bar;

    another simple way and will give you more control as you can add more conditions and assign to another variable in the same time

    $foo = (isset($oData['foo']))?$bar['foo']:'default value';

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