If first argument falls true in a condition with and operators will the next run?
Lets say I've got a pice of code that looks like this:
if( !isset($this->domainID) && !$this->getDomainID() ){
return false;
}
Will the 2nd statement run if the first one is true? Because performance wise it would be stupid to get the ID from the database if I've already got it and there's a lot of o开发者_运维问答ther situation where the same apply. If it doesn't I'd have to nest them, am I right?
I don't know if there's an standard on how programming language work in these cases or if it's different in other languages then php. I tried googling it but I didn't really know what to search for in this case. As you can see I hade a quite hard time describing it in the title.
Yes. If the first is true, the second will be evaluated. Conversely, if the first is false, the second will not be evaluated. This can be a good place for micro optimizations and, as you noted, logical progression.
Per the comments, the inverse is true for OR conditions. So if the first expression is false the next will be evaluated and if the first expression is true the next will not.
No, if the first is false, the second will not be evaluated.
What you're really talking about here is "lazy evaluation". It's often used in functional programming languages and can vastly improve the run-time. See here for more info: http://en.wikipedia.org/wiki/Lazy_evaluation
PHP does not use lazy evaluation but in conditionals like this it does at least stop before the second argument if the result is already clear.
Answer is yes, you can see it by yourself by doing something like this:
#!/usr/bin/php
<?PHP
function test1() {
echo "inside test1\n";
return false;
}
function test2() {
echo "inside test2\n";
return true;
}
echo "test1 first AND test2 second\n";
if (test1() && test2()) {
echo "both passed\n";
}
echo "test2 first AND test1 second\n";
if (test2() && test1()) {
echo "both passed\n";
}
echo "test1 first OR test2 second\n";
if (test1() || test2()) {
echo "one passed\n";
}
echo "test2 first OR test1 second\n";
if (test2() || test1()) {
echo "one passed\n";
}
?>
Yes, you are using an AND so both conditions will be checked if the first is true (but not if the first is false).
If you had used an OR and the first condition was true, php wouldn't evaluate the second.
精彩评论