Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

logic - Is there a short-circuit OR in PHP that returns the left-most value?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...