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

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

提交回复
热议问题