In what order are conditions inside an IF checked?

I had a problem were I need to check two conditions, A and B. The thing is, checking B takes a lot of time, and if A is already false I don't need to check for B. I can easily do:

if(a)
  if(b)
    // Do something

But I wonder, if I do if(a AND b) , does the PHP interpreter check for A and B and then apply the AND operator? Or does it already "know" there is an AND operator and so if A is false it does not checks for B?


What you are talking about is called Short-Circuit evaluation. I am not a PHP expert but a quick search on google explains that it is implemented in PHP. So, if A is false, B will not be executed.

http://en.wikipedia.org/wiki/Short-circuit_evaluation


You can use "lazy evaluation" like this:

if (A && B) {
   //do shomething..
}

The "B" expression will evaluate only when the "A" expression is true.


Depends on the language. PHP Will stop evaluating as soon as it knows the result will be false which means you can do...

if($connection->connected() and $connection->doSomething()) {

}

It will on do doSomething() if it's connected.

链接地址: http://www.djcxy.com/p/57640.html

上一篇: 从用户网站输入获取网站标题

下一篇: IF中的条件按什么顺序检查?