0

Possible Duplicate:
PHP short circuit lazy evaluation, where is it in the php.net manual?
PHP “or” Syntax

I have seen people using the || operator as program flow control as follows:

function() || die("message");

where die("message"); will run if function() returns false. Furthermore, it seems to only work for die(); and exit(); else the interpreter will throw a "syntax error" message.

I'm wondering what this is called and where can I find documentation for its behaviour.

Jonas
  • 121,568
  • 97
  • 310
  • 388
John
  • 3
  • 1
  • 1
    You should have no problem using this for any function. This just a simple boolean OR. – Michael Mior Mar 09 '12 at 19:19
  • For reference the first time I saw it was in a mysql database connection script where they have `mysql_select_db($database, $connection) || die(mysql_error()) ;` – John Mar 09 '12 at 19:20
  • It's a rather confusing "clever trick". I'd avoid it for the sake of maintainability. – rid Mar 09 '12 at 19:21
  • @John You could easily define your own functions and do `foo() || bar()`. There's no special treatment of `exit` or `die`. – Michael Mior Mar 09 '12 at 19:22
  • 1
    It does not only work for `die` and `exit`. It works for *expressions* (where function calls are one option). Commonly `or` is preferred over `||` however. – mario Mar 09 '12 at 19:22
  • http://en.wikipedia.org/wiki/Short-circuit_evaluation – Dagg Nabbit Mar 09 '12 at 19:22
  • Don't use [`or die`](http://www.phpfreaks.com/blog/or-die-must-die) when outputting HTML. You'll get invalid HTML. – outis Mar 10 '12 at 15:46

3 Answers3

1

It's just a boolean OR expression. The usage is taking advantage of a behavior called short cutting, where if the first part of the expression evaluates to true, then the second half isn't evaluated because the OR expression is already true.

jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
0

It's just logic OR. If function() returns true, then the rest of the expression is not evaluated.

rid
  • 61,078
  • 31
  • 152
  • 193
  • Ah I get it now, it didn't occur to me that shortcircuit evaluations work outside of control expressions. Thanks. – John Mar 09 '12 at 19:26
0

This is due to OR / || being an operator with left precedence (see here: http://www.php.net/manual/en/language.operators.precedence.php) as the left is evaluated to be true, there is no point in evaluating the right side as the expression will always be true.

Ingmar Boddington
  • 3,440
  • 19
  • 38