有条件地分配PHP值

问题描述 投票:20回答:4

对于基于表达式结果为变量赋值的常见情况,我是三元运算符的粉丝:

$foo = $bar ? $a : b;

但是,如果$ bar是一个相对昂贵的操作,并且如果结果是真的,我想将$ bar的结果赋给$ foo,这是低效的:

$foo = SomeClass::bigQuery() ? SomeClass::bigQuery() : new EmptySet();

一种选择是:

$foo = ($result = SomeClass::bigQuery()) ? $result : new EmptySet();

但我宁愿没有额外的$result坐在记忆中。

我得到的最好选择是:

$foo = ($foo = SomeClass::bigQuery()) ? $foo : new EmptySet();

或者,没有三元运算符:

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

或者,如果程序流操作符不是您的风格:

($foo = SomeClass::bigQuery()) || ($foo = new EmptySet());

这么多选择,非他们真的令人满意。你会使用哪种,我错过了一些非常明显的东西?

php ternary-operator
4个回答
38
投票

PHP 5.3引入了一种新的语法来解决这个问题:

$x = expensive() ?: $default;

documentation

从PHP 5.3开始,可以省略三元运算符的中间部分。 如果expr1 ?: expr3评估为expr1,则表达式expr1返回TRUE,否则返回expr3


8
投票

你能更新SomeClass:bigQuery()来返回一个新的EmptySet()而不是false吗?

那你就是

$foo = SomeClass::bigQuery();

1
投票

您最后一个选项略有不同:

$ foo = SomeClass :: bigQuery()或new EmptySet(); 这实际上不起作用,感谢您的注意。

经常与mySQL代码结合使用,但在类似的情况下似乎总是被遗忘:

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

虽然我个人更喜欢你已提到过的一个:

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

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

修订版2,信用@meagar

© www.soinside.com 2019 - 2024. All rights reserved.