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.

7
  • 1
    You should have no problem using this for any function. This just a simple boolean OR. Commented Mar 9, 2012 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()) ; Commented Mar 9, 2012 at 19:20
  • It's a rather confusing "clever trick". I'd avoid it for the sake of maintainability. Commented Mar 9, 2012 at 19:21
  • @John You could easily define your own functions and do foo() || bar(). There's no special treatment of exit or die. Commented Mar 9, 2012 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. Commented Mar 9, 2012 at 19:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Ah I get it now, it didn't occur to me that shortcircuit evaluations work outside of control expressions. Thanks.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.