有条件地分配PHP值 [英] Conditionally assigning PHP values

查看:61
本文介绍了有条件地分配PHP值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非常常见的情况下,根据表达式的结果为变量赋值,我是三元运算符的爱好者:

  $ foo = $ bar? $ a:b; 

但是,如果$ bar是一个相对昂贵的操作,我想将$ bar的结果赋给$ foo如果结果为真,则效率低下:

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

一个选项是:

  $ foo =($ result = SomeClass :: bigQuery())吗? $ result:newEmptySet(); 

但是我宁愿没有多余的 $ result 坐在内存中。



我最好的选择是:

  $ foo =($ foo = SomeClass :: bigQuery())吗? $ foo:新的EmptySet(); 

或者,没有三元运算符:

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

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

 ($ foo = SomeClass :: bigQuery())|| ($ foo =新的EmptySet()); 

这么多的选择,没有一个真的令人满意。您将使用哪一个,而我在这里确实遗漏了一些明显的东西? :

  $ x = cheaper()?:$ default; 

请参见文档


自PHP 5.3起,可以省略三元运算符的中间部分。
表达式 expr1?:expr3 如果 expr1 expr1 >的值为 TRUE ,否则为 expr3



For the very common case of assigning a value to a variable based on the outcome of an expression I'm a fan of ternary operators:

$foo = $bar ? $a : b;

However, if $bar is a relatively expensive operation and I want to assign the result of $bar to $foo if the result is truthy, this is inefficient:

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

One option is:

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

But I'd rather not have the extra $result sitting in memory.

The best option I've got is:

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

Or, without ternary operators:

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

Or, if program flow operators are not your style:

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

So many options, non of them really satisfactory. Which would you use, and am I missing something really obvious here?

解决方案

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.

这篇关于有条件地分配PHP值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆