Does PHP have a default assignment idiom like perl?

前端 未结 3 1115
孤街浪徒
孤街浪徒 2020-12-20 19:29

In Perl, if I want to default a value that might exist, for example as a passed in parameter, I can do this:

  $var = parm->(\'variable\') || \'default\';         


        
3条回答
  •  攒了一身酷
    2020-12-20 20:12

    Not exactly.

    PHP 5.3 introduced what they call "the ternary shortcut".

    // old way
    $foo = $foo ? $foo : 'default';
    
    // new way in 5.3
    $foo = $foo ?: 'default';
    

    Which isn't even that much of a shortcut and only works short-circuit-able values (if 0 is a valid value for $foo this shortcut will fail.)

    Otherwise you'll have to do the type/existence checking the old, hard, manual way.

    You can also specify default values for parameters in the signature - not sure if that's exactly what you're getting at but here's that in action

    function foo( $bar = 'baz' )
    {
      echo $bar;
    }
    
    foo(); // baz
    

提交回复
热议问题