PHP shorthand logical operators AND and OR
Possible Duplicates:
PHP - and / or keywords
PHP shorthand syntax
Quick question. I keep seeing shorthand expressions in libraries around the place, and despite having been a PHP developer for over 3 years, I struggle to quite see how the following would evaluate.
What exactly does the PHP interpreter do with the following shorthand lines of code when it encounters them?
<?php
defined('foo') OR exit('foo is not defined!');
$foo AND $this->bar();
I'm guessing that it' obviously conditional execution - ie the second statement won't get executed unless the first bit is true... but the use of the bitwise operators confuse me a bit.
Can someone elaborate?
Thanks :)
Back when I was learning PHP I remember reading the 'do or die' style commands and not fully understanding them at the time, the classic example is:
mysql_connect() or die('couldn't connect');
Bear in mind that the conditions will only run if they're required, for example:
if (a == b && b == c)
Here b == c will only be tested if a == b. The same theory applies to or:
if (a == b || b == c)
Now b == c will only be tested if a != b.
In this case you are relying on this order to run a command (exit or $this->bar()) in certain conditions.
Be Aware... exit() is a bad idea in this circumstance - if you exit('something went wrong') there's nothing anyone can do to hide this error from the user, also it's likely to issue a 200 OK HTTP status where a 500 Internal Server Error would be much more appropriate, I would consider something more like:
defined('foo') OR throw new Exception('foo is not defined!');
Here you have a chance to either catch the Exception or at least let PHP catch it and issue a 500 status.
Mat
I believe that this is a form of short-circuit evaluation: http://en.wikipedia.org/wiki/Short-circuit_evaluation
Essentially, when evaluating an entire expression, the interpreter short circuits once it is certain of the result. For example:
true OR do_something();
This expression never calls do_something() because the first operand of OR is true, so the entire expression must be true.
Much less elaborate than you think. The or
keyword is the same as ||
, except it has lower precedence. See the corresponding PHP page for details.
The actual execution of this statement relies on a separate concept involving logical operators: short circuiting. This means that, in the case of or
, the second statement is not evaluated if the first statement turns out to be true. (Since in a conditional, for instance, the entire condition would return true without ever needing to see the second half.)
上一篇: “或”在PHP中是什么意思?
下一篇: PHP简写逻辑运算符AND和OR