PHP中是否有短路OR返回最左边的值? [英] Is there a short-circuit OR in PHP that returns the left-most value?

查看:52
本文介绍了PHP中是否有短路OR返回最左边的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些语言中,您可以

$a = $b OR $c OR die("no value");

也就是说,OR将短路,仅从左到右评估值,直到找到真值为止.但除此之外,它返回的是被评估的 the 实际值,而不仅仅是true.

That is, the OR will short-circuit, only evaluating values from left to right until it finds a true value. But in addition, it returns the actual value that was evaluated, as opposed to just true.

在上面的示例中,在PHP中,如果$a$b是非假值,则$a将是值1,否则将是die.

In the above example, in PHP, $a will be the value 1 if either $a or $b are non-false values, or it will die.

于是写了一个函数first用作

$a = first($a, $b, die("no value"));

返回$a$b.但是,它不会短路-总是die.

which returns the value of either $a or $b. But, it does not short-circuit - it will always die.

PHP中是否有短路OR返回实际值?

Is there a short-circuit OR in PHP that returns the actual value?

对于我给出的示例,一些很好的答案,但是我想我的示例与我的意思并不完全相同.让我澄清一下.

Some good answers for the example I gave, but I guess my example isn't exactly what I meant. Let me clarify.

$a = func1() OR func2() OR func3();

这些函数中的每一个都进行真正非常密集的计算,所以我只想对每个表达式最多计算一次.对于第一次返回真实值的情况,我希望将实际值存储在$a中.

Where each of those functions does a really really intense computation, so I only want to evaluate each expression once at most. And for the first to return a true value, I want the actual value to be stored in $a.

我认为我们可以排除编写函数的麻烦,因为它不会短路.并且条件运算符答案将对每个表达式进行两次评估.

I think we can rule out writing a function, because it won't short-circuit. And the conditional operator answer will evaluate each expression twice.

推荐答案

您可以使用:

$a = func1() or $a = func2() or $a = func3();

还是我错过了什么?

这篇关于PHP中是否有短路OR返回最左边的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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