对于基于表达式的结果为变量赋值的非常常见的情况,我是三元运算符的粉丝:
$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());
这么多选择,没有一个真的令人满意。您会使用哪个,我是否在这里遗漏了一些非常明显的东西?