Early in his career, every PHP programmer writes code like:
mysql_query( $sql ) or die( mysql_error() );
Come on! We’ve all been there. Of course, now we all agree that that’s lame and stupid and we use PDO or even ActiveRecord, but back in the days, that was widely used. What does that mean, actually? or die()?
It’s an optimization originally implemented in C++ – I think – gone wild.
For instance, if you have a condition like:
if ( ( $a == $b ) || ( $c == $d ) ) { /* whatever */}
…if the the result in the first set of parenthesis evaluates to true, the second one isn’t evaluated because its result is irrelevant in this context. The parser already knows the answer, as “true or anything” always equals true.
The mysql_query() function returns a value that can be evaluated from a boolean point of view. If that result is evaluated to true (the query was okay), then the die() part gets left out. If the query fails and mysql_query() returns something that evaluates as false, then the die() call gets executed. That’s all, in a nutshell.
The above code could have been rewritten as:
if ( ! mysql_query( $sql ) ) {
die( mysql_error() );
}
Still lame, but with improved readability.
Of course, you can do nifty tricks with this kind of constructs:
is_numeric ( $_GET['id'] ) || redirect( '/my/error/url' );
Cool!
I really like short-circuit logic!
Yep. But if you’re using juniors on the project, they may react unexpectedly to the sight of this code.
It depends. If they have basic boolean algebra knowledge, they might not be confused by that code. But then again, some of them have problems, as you mentioned in one of your previous posts, with the ++/– operators. >:)
Dude, I’ve seen so called “seniors programmers” having these kind of flaws…
There are some guys using some other trick, which may be useful sometimes. Personally, I’ve never used it.
Yeap, but it relies on the same thing…