Does PHP have a default assignment idiom like perl?

前端 未结 3 1114
孤街浪徒
孤街浪徒 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
    
    0 讨论(0)
  • 2020-12-20 20:25
    $var = (!empty($foo)) ? $foo : 'default';
    
    0 讨论(0)
  • 2020-12-20 20:36

    I think the standard ternary is defacto in PHP:

    $var = $foo ? $foo : 'default';
    echo $foo ? $foo : 'default';
    

    But there are a couple other tricks that can be a little cleaner in some cases:

    //these are very close but can't be echo'd inline like a ternary
    $var = $foo OR $var = 'default';//assigning a default to $var if $foo is falsy
    ($var = $foo) || $var = 'default';//same effect as above
    
    isset($var) || $var = 'default';//making sure $var is set
    

    Here's one that can be echo'd inline:

    $var = ($foo) ?: 'default';//partial ternary
    echo ($foo) ?: 'default';//aka ternary shortcut (PHP 5.3+ only)
    

    An important note is that a lot of these can emit errors when vars are not set :(

    echo @($foo) ?: 'default';//@ fixes it but isn't considered good practice
    

    One place it may be worth not using the ternary approach is when they're nested:

    $user = (($user)?$user:(($user_name)?$user_name:(($user_id)?$user_id:'User')));
    echo 'Welcome '.$user;//is pretty messy
    
    ($user = $user) || ($user = $user_name) || ($user = $user_id) || ($user = 'User');
    echo 'Welcome '.$user;//is more readable
    

    Anyway, lot's of fun to explore.

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