Is 'or' treated as a boolean check on the return of a statement?
A common way of handling a failure is:
$result = mysql_query("SELECT * FROM table1") or myFailureFunction();
The result being that when the query fails, myFailureFunction()
gets called.
Is there any case where the following code isn't exactly the same?
$result = mysql_query("SELECT * FROM table1");
if(!$result)
{
myFailureFunction();
}
Notes:
- I have tested with connection failure, SQL syntax failure and empty results and it seems to work for all of them. I'm wondering is there any case that it won't work for.
- I know there are much better ways to handle failure.
- There is a question that addresses the boolean nature of
or
. What I'm wondering is, is theor
operating on the resturned result or something else? Q开发者_JS百科uestion: PHP: 'or' statement on instruction fail: how to throw a new exception?
In your case, they are exactly the same because of short circuit evaluation, however if null or some other falsey vale is returned, it will make a difference. Note:
function f(){return false;}
function w(){return "w";}
$a = f() or w();
echo isset($a);
// 1 (true). $a === FALSE!
Now, note what happens with a lack of a return:
function f(){}
function w(){return "w";}
$a = f() or w();
echo isset($a);
// nothing (false)
They're practically equivalent. The only difference is that $result
is undefined after the longer version, while it will have the value FALSE
after the shorter version.
PHP, like most languages, implements boolean operations using short-circuit evaluation. If the left hand-value is true, it won't evaluate the right-hand value, so the function won't run. The left-hand value is FALSE
if any error occurs, so causes the right-hand side to be evaluated.
They're exactly equivalent. the failure function will only get called if mysql_query returns a boolean false. PHP uses short-circuit boolean evaluation in this case. Once it has enough data to figure out what the boolean result of the whole expression is, it stops evaluating the rest of it.
Consider what would happen if PHP didn't short-circuit this:
$result = mysql_query(...) or die(mysql_error());
If both sides were evaluated/executed, then the script would die, even if the query itself didn't return false.
Both statements are the same. PHP uses short-circuit evaluation for boolean expressions. That means it only evaluates the expressions when the first expression was false. That's the reason you can use it as simple control structures. or
also has very low precedence
OR is operating in the "is not 0" (or in this case, not null) sense, which is common to many languages including C++. From http://www.intap.net/~drw/cpp/cpp03_04.htm,
It is perfectly legal in C++ to use boolean operators on variables which are not booleans. In C++, "0" is false and any non-zero value is true.
精彩评论