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

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

    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.

提交回复
热议问题