18

Sorry if this sounds like a really silly question.

But I Googled the web and also Googled specifically both the php.net site and the stackoverflow.com site. I know PHP does short circuit lazy evaluation when using and, or, &&, || operators, but where is it stated loud and clear in the PHP manual???

I found only Wikipedia as the only 'trusted' source that say PHP does lazy evaluation on these operators.

Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
  • I don't know where it's written either, but it's taken for granted a good number of times, for instance when people call like `mysql_connect(...) || die("Connection failed");`. – zneak Jul 10 '10 at 21:38
  • The most trustworthy source is the source code itself. And as far as I remember from the last time I read it, it's true. – Ionuț G. Stan Jul 10 '10 at 21:39
  • Does it matter that it's said to be official or not? It's the way PHP works, code with that idea in mind. – Matt S Jul 10 '10 at 21:42
  • 2
    Hugh, my question wasn't that silly since someone placed a +1 vote. – Marco Demaio Jul 10 '10 at 21:55
  • 6
    +1: It's a very reasonable concern. It's certainly possible to program without a clear spec, relying on inferences from code examples, hearsay about the intentions of the designers, and poking around the details of the current implementation. But anyone who has to work like that is entitled to worry that their house is built on sand. –  Aug 19 '11 at 01:58
  • Wow. This explains so many inexplicable cases where I've had to nest conditionals instead of putting them all in one test. – Winfield Trail Sep 25 '12 at 17:57

2 Answers2

9

Closest thing I can find to an 'official' mention of PHP's short-circuit implementation: http://php.net/manual/en/language.operators.logical.php

Mike B
  • 31,886
  • 13
  • 87
  • 111
  • 3
    It's written inside the code snippet. First comment: `// foo() will never get called as those operators are short-circuit` – zneak Jul 10 '10 at 21:39
  • Thanks for the help!!! It's not stated loud and clear, but it's written there and also with clear examples. – Marco Demaio Jul 10 '10 at 21:53
  • How about short-circuiting for `?:`? Come on, PHP, look at [Java](http://stackoverflow.com/a/978357/1402846). – Pang Mar 12 '15 at 05:18
1

This is not an uncommon feature of expression evaluation. The PHP manual page on logical operators makes a passing reference to it in one of the illustrative examples though.

Short circuit evaluation is a commonly exploited idiom, and you can rely on its continued support in the language, otherwise vast amounts of code would break!

Paul Dixon
  • 295,876
  • 54
  • 310
  • 348