Conditionally assigning PHP values

泪湿孤枕 提交于 2019-12-01 02:46:30

PHP 5.3 introduced a new syntax to solve exactly this problem:

$x = expensive() ?: $default;

See the documentation:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator.
Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Can you update SomeClass:bigQuery() to return a new EmptySet() instead of false?

Then you just have

$foo = SomeClass::bigQuery();

A slight variation of your last option:

$foo = SomeClass::bigQuery() or new EmptySet(); this doesn't actually work, thanks for noticing.

Used often in combination with mySQL code, but seems always forgotten in comparable situations:

$result = mysql_query($sql) or die(mysql_error());

Although personally I prefer one you already mentioned:

if(!$foo = SomeClass::bigQuery())
    $foo = new EmptySet();
$foo = SomeClass::bigQuery();
if (!$foo) $foo = new EmptySet();

Revision two, credit @meagar

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