PHP 中是否有返回最左边值的短路 OR?
在某些语言中,你可以这样做
$a = $b OR $c OR die("no value");
也就是说,OR 会短路,只从左到右评估值,直到它找到一个真正的值。但除此之外,它还返回被评估的实际值,而不是仅仅返回 true。
在上面的示例中,在 PHP 中,如果 $a
或 $b
则 $a
将为值 1
是非假值,否则它将死亡
。
因此编写了一个函数 first
,用作
$a = first($a, $b, die("no value"));
,
它返回 $a
或 $b
的值。但是,它不会短路 - 它总是会死亡
。
PHP 中是否有返回实际值的短路 OR
?
编辑: 我给出的例子有一些很好的答案,但我想我的例子并不完全是我的意思。让我澄清一下。
$a = func1() OR func2() OR func3();
其中每个函数都执行非常非常密集的计算,因此我只想对每个表达式求值一次最多。对于第一个返回真值的情况,我希望将实际值存储在 $a
中。
我认为我们可以排除编写一个函数,因为它不会短路。条件运算符的答案将对每个表达式求值两次。
In some languages, you can do
$a = $b OR $c OR die("no value");
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
.
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
.
So wrote a function first
, to be used as
$a = first($a, $b, die("no value"));
which returns the value of either $a
or $b
. But, it does not short-circuit - it will always die
.
Is there a short-circuit OR
in PHP that returns the actual value?
Edit:
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();
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,没有,在我看来,这是 Rasmus Lerdorf 在设计 PHP 时做出的错误决定之一,大多数人为了溺爱无能的开发人员而阻碍了有能力的开发人员。
编辑:在 PHP 5.3 及更高版本中,您可以编写
$a = $b ?: $c
,甚至$a = $b ?: $c ?: $d
。仍然不如非脑损伤的逻辑运算符,但它是一些东西。No, there isn't, and this is, in my opinion, one of the bad decisions that Rasmus Lerdorf made in designing PHP that most hobbles competent developers for the sake of coddling incompetent ones.
Edit: In PHP 5.3 and up, you can write
$a = $b ?: $c
, and even$a = $b ?: $c ?: $d
. Still not as good as non-brain-damaged logical operators, but it's something.你可以只使用:
或者我错过了什么?
You can use just:
or am I missing something?
您可以使用某种
coalesce
函数 :You could use some kind of
coalesce
function:变量函数呢?
What about variable functions?
抱歉,这些答案大部分都是错误的。
$a = $b 或 $c 或 die("无值");
。
OR 不起作用的原因是,它不是返回前一个值或后一个值,而是返回 true 或 false
I'm sorry, but most of these answer are just off.
$a = $b OR $c OR die("no value");
becomes
The reason OR doesn't work is that instead instead of returning the former or latter value it returns true or false.
这应该有效:
This should work: