PHP assignment with a default value

北慕城南 提交于 2019-12-05 17:38:40

问题


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

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

回答1:


In PHP 5.3, you can also do:

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

See the manual on ?: operator.




回答2:


This seems to work fine:

$x = f() or $x = 'default';



回答3:


function f()
{
  // conditions 
  return $if_something ? $if_something : 'default';
}

$x = f();



回答4:


$x = ($result = foo()) ? $result : 'default';

test




回答5:


You could save it to a variable. Testcase:

function test() {
        echo 'here';
        return 1;
}

$t = test();
$x = $t ? $t : 0;
echo $x;


来源:https://stackoverflow.com/questions/4832114/php-assignment-with-a-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!