PHP 有短路评估吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5694733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does PHP have short-circuit evaluation?
提问by Muntasir
Given the following code:
鉴于以下代码:
if (is_valid($string) && up_to_length($string) && file_exists($file))
{
......
}
If is_valid($string)
returns false
, does the php interpreter still check later conditions, like up_to_length($string)
?
If so, then why does it do extra work when it doesn't have to?
如果is_valid($string)
返回false
,php 解释器是否仍然检查后面的条件,比如up_to_length($string)
?
如果是这样,那么为什么它不需要做额外的工作呢?
回答by Zach Rattner
Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.
是的,PHP 解释器是“懒惰的”,这意味着它会进行尽可能少的比较来评估条件。
If you want to verify that, try this:
如果您想验证这一点,请尝试以下操作:
function saySomething()
{
echo 'hi!';
return true;
}
if (false && saySomething())
{
echo 'statement evaluated to true';
}
回答by Robert
Yes, it does. Here's a little trick that relies on short-circuit evaluation. Sometimes you might have a small if statement that you'd prefer to write as a ternary, e.g.:
是的,它确实。这是一个依赖短路评估的小技巧。有时您可能有一个小的 if 语句,您更愿意将其写为三元,例如:
if ($confirmed) {
$answer = 'Yes';
} else {
$answer = 'No';
}
Can be re-written as:
可以改写为:
$answer = $confirmed ? 'Yes' : 'No';
But then what if the yes block also required some function to be run?
但是,如果 yes 块还需要运行某些函数呢?
if ($confirmed) {
do_something();
$answer = 'Yes';
} else {
$answer = 'No';
}
Well, rewriting as ternary is still possible, because of short-circuit evaluation:
好吧,由于短路评估,仍然可以重写为三元:
$answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';
In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true
, ignoring the return value of do_something()
.
在这种情况下,表达式 (do_something() || true) 不会改变三元的整体结果,但确保三元条件保持不变true
,忽略 的返回值do_something()
。
回答by Steve Douglas
Bitwise operatorsare &
and |
.
They always evaluate both operands.
按位运算符是&
和|
。他们总是评估两个操作数。
Logical operatorsare AND
, OR
, &&
, and ||
.
逻辑运算符是AND
,OR
,&&
,和||
。
- All four operators only evaluate the right side if they need to.
AND
andOR
have lower precedence than&&
and||
. See example below.
- 所有四个运算符仅在需要时评估右侧。
AND
并且OR
具有比&&
and低的优先级||
。请参阅下面的示例。
From the PHP manual:
从 PHP 手册:
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;
In this example, e
will be true
and f
will be false
.
在这个例子中,e
will betrue
和f
will be false
。
回答by agm1984
Based on my research now, PHP doesn't seem to have the same &&
short circuit operator as JavaScript.
根据我现在的研究,PHP 似乎没有&&
与 JavaScript相同的短路运算符。
I ran this test:
我运行了这个测试:
$one = true;
$two = 'Cabbage';
$test = $one && $two;
echo $test;
and PHP 7.0.8 returned 1
, not Cabbage
.
和 PHP 7.0.8 返回1
,而不是Cabbage
。
回答by Obay
No, it doesn't anymore check the other conditions if the first condition isn't satisfied.
不,如果第一个条件不满足,它不再检查其他条件。
回答by Perspective
I've create my own short-circuit evaluation logic, unfortunately it's nothing like javascripts quick syntax, but perhaps this is a solution you might find useful:
我已经创建了自己的短路评估逻辑,不幸的是它不像 javascripts 快速语法,但也许这是一个您可能会发现有用的解决方案:
$short_circuit_isset = function($var, $default_value = NULL) {
return (isset($var)) ? : $default_value;
};
$return_title = $short_circuit_isset( $_GET['returntitle'], 'God');
// Should return type 'String' value 'God', if get param is not set
I can not recall where I got the following logic from, but if you do the following;
我不记得我从哪里得到以下逻辑,但是如果您执行以下操作;
(isset($var)) ? : $default_value;
You can skip having to write the true condition variable again, after the question mark, e.g:
您可以跳过必须在问号之后再次编写 true 条件变量的步骤,例如:
(isset($super_long_var_name)) ? $super_long_var_name : $default_value;
As very important observation, when using the Ternary Operatorthis way, you'll notice that if a comparison is made it will just pass the value of that comparison, since there isn't just a single variable. E.g:
作为非常重要的观察,当以这种方式使用三元运算符时,您会注意到如果进行比较,它只会传递该比较的值,因为不仅仅是一个变量。例如:
$num = 1;
$num2 = 2;
var_dump( ($num < $num2) ? : 'oh snap' );
// outputs bool 'true'
回答by Beto Aveiga
My choice: do nottrust Short Circuit evaluation in PHP...
我的选择:不要相信 PHP 中的短路评估...
function saySomething()
{
print ('hi!');
return true;
}
if (1 || saySomething())
{
print('statement evaluated to true');
}
The second part in the condition 1 || saySomething()is irrelevant, because this will always return true. Unfortunately saySomething()is evaluated & executed.
条件1 中的第二部分|| saySomething()无关紧要,因为这将始终返回 true。不幸的是saySomething()被评估和执行。
Maybe I'm misunderstood the exact logic of short-circuiting expressions, but this doesn't look like "it will do the minimum number of comparisons possible"to me.
也许我误解了短路表达式的确切逻辑,但这对我来说看起来不像“它会进行尽可能少的比较”。
Moreover, it's not only a performance concern, if you do assignments inside comparisons or if you do something that makes a difference, other than just comparing stuff, you could end with different results.
此外,这不仅是一个性能问题,如果您在比较中进行赋值,或者如果您做了一些不同的事情,而不仅仅是比较东西,您可能会得到不同的结果。
Anyway... be careful.
总之……小心点。
回答by Patricio Rossi
Side note:If you want to avoid the lazy check and run every part of the condition, in that case you need to use the logical AND like this:
旁注:如果您想避免延迟检查并运行条件的每个部分,在这种情况下,您需要像这样使用逻辑 AND:
if (condition1 & condition2) {
echo "both true";
}
else {
echo "one or both false";
}
This is useful when you need for example call two functions even if the first one returned false.
这在您需要例如调用两个函数时很有用,即使第一个函数返回 false。