Search code examples
phpexceptionthrowdie

Newer version of "... or die(..."


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.


Solution

  • 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.