3

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 will cause the program run the or die()?

Community
  • 1
  • 1
Tattat
  • 15,548
  • 33
  • 87
  • 138

5 Answers5

9

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

or is equal to || except that || has a higher presedense than or.

Reference:

http://www.php.net/manual/en/language.operators.precedence.php

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
1

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");
GAgnew
  • 3,847
  • 3
  • 26
  • 28
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0

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.

GAgnew
  • 3,847
  • 3
  • 26
  • 28
  • 1
    Its not similar to `try-catch`. – KingCrunch Apr 21 '11 at 17:16
  • _Similar_ to try catch as in, it trys the first statement, and on false, executes the second. Or on true, does not execute the second statement, or 'catch'. I was commenting on the posters question 'Why would you use this instead of a try catch block? ' Where as try/catch is on error, this is on boolean. – GAgnew Apr 25 '11 at 05:38
-1

Yes it equals ||

In this case it is explicitly stopping the execution of the page and printing that error message.

Gho5t
  • 1,060
  • 1
  • 12
  • 23