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

后端 未结 8 1358
眼角桃花
眼角桃花 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: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.

提交回复
热议问题