Possible Duplicate:
PHP - and / or keywords
I saw several bits of PHP code using or
in a way I was unfamiliar with. For example:
fopen($site,"r") or die("Unable to connect to $site");
Is this equal to this ||
?
Why would you use this instead of a try catch
block? What开发者_如何学Go will cause the program run the or die()
?
It is for the most part, but...
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences.
See http://php.net/manual/en/language.operators.logical.php
or
is equal to ||
except that ||
has a higher presedense than or
.
Reference:
http://www.php.net/manual/en/language.operators.precedence.php
or
has an other precedence. The concrete statement is little trick with boolean operators. Like in a common if
-test-expression the second part is only executed, if the first is evaluated to false
. This means, if fopen()
does not fail, die()
is not touched at all.
However, try-catch
only works with Exceptions, but fopen()
doesnt throw any.
Today something like this is "not so good" style. Use exceptions instead of hard abortion
if (!($res = fopen($site, 'r'))) throw new Exception ("Reading of $site failed");
or die happens with the first command fails.
It is similar to a try catch, but this is more direct approach.
Note that this is a classical test:
fopen($site,"r") or die("Unable to connect to $site");
Only if fopen($site,"r") returns false, will the second half of the test be run: 'die('error')'.
Same is if(a || b); b is only run if a returns false.
Die in PHP is the same as exit(); http://www.php.net/manual/en/function.exit.php
Stops execution of the current script entirely, and prints out the error message.
Yes it equals ||
In this case it is explicitly stopping the execution of the page and printing that error message.
精彩评论