views:

59

answers:

2

A long time ago I used to use "or die" in my PHP code. Especially like this:

$q = mysql_query('......') or die(mysql_error());

Obviously, that's pretty shameful these days, but the X or Y principle still speaks to me. So I though I'd try this:

$r = $this->exec($query) or throw new Exception('FAIL');

but that results in a parse error! What's the best practice for such statements. It has to look nice as well (obviously!)...

I don't like

if ( !($r = $this->exec($query)) ) throw new ...

or

$r = $this->exec($query)
if ( !$r ) throw new ....

Any favourites? Discouragements? Best practices? Speed is always nice.

+2  A: 

There's nothing wrong with the two examples you used, except that you've sandwitched them onto one line.

I'm not sure what you're looking for, or why you're finding fault with an if statement - it's pretty tried and true at this point. That said, you can do something like this to shoe-horn in the or operator, but whoever maintains your code after you're gone will curse you.

function throw_ex($what) {
  throw $what;
}

function fails() {
  return false;
}

$x = fails() or throw_ex(new exception("failed"));

I don't see how this gains you anything over the ol' if statement.

meagar
It's not the "fastest" solution either because of the extra function call. If statements are definitely the best
GWW
I guess you're right. I was just looking for something slick :) Also wondering why "or throw Exception" wouldnt work, but "or die" and " or soSomeFunction" do work. I'm gonne go with the first one I dont like then.
Rudie
+1  A: 

Fact of the matter is, you should be using if statements to catch actual, recoverable errors. Especially if you are using InnoDB which can sometimes have deadlocks during normal operation and the proper way to handle them isn't to die(), but simply submit the query again.

More info here: http://arjen-lentz.livejournal.com/150464.html

rekamso