PHP assignment with a default value

前端 未结 5 2135
春和景丽
春和景丽 2021-02-20 01:48

What\'s a nicer way to do the following, that doesn\'t call f() twice?

$x = f() ? f() : \'default\';
相关标签:
5条回答
  • 2021-02-20 02:04

    In PHP 5.3, you can also do:

      $a = f() ?: 'default';
    

    See the manual on ?: operator.

    0 讨论(0)
  • 2021-02-20 02:05
    function f()
    {
      // conditions 
      return $if_something ? $if_something : 'default';
    }
    
    $x = f();
    
    0 讨论(0)
  • 2021-02-20 02:11

    This seems to work fine:

    $x = f() or $x = 'default';
    
    0 讨论(0)
  • 2021-02-20 02:14

    You could save it to a variable. Testcase:

    function test() {
            echo 'here';
            return 1;
    }
    
    $t = test();
    $x = $t ? $t : 0;
    echo $x;
    
    0 讨论(0)
  • 2021-02-20 02:18
    $x = ($result = foo()) ? $result : 'default';
    

    test

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