Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP old-school function "or" with exception [duplicate]

Possible Duplicate:
PHP: 'or' statement on instruction fail: how to throw a new exception?

In PHP, especially popular amongst the newbies in various MySQL connection tutorials, you've always been able to do something like this...

<?php
foo() or die('foo() failed!');
?>

However if I try something like this it fails...

<?php
foo() or throw new Exception('AHH!');
?>

Like so...

"Parse error: syntax error, unexpected 'throw' (T_THROW) in..."

Anybody know how to do something similar to this? Would I have to set a variable after the "or"?

like image 773
TheFrack Avatar asked Oct 05 '12 17:10

TheFrack


1 Answers

Do it the less "clever" way:

if(!foo()) {
    throw new Exception('AHH!');
}

In case you're wondering why or throw new Exception() doesn't work, it's because you're relying on the short-circuiting of the or operator: If the first argument is true, then there's no need to evaluate the second to determine if one of them is true (since you already know that at least one of them is true).

You can't do this with throw since it's an expression that doesn't return a boolean value (or any value at all), so oring doesn't make any sense.

If you really want to do this, the deleted answer by @emie should work (make a function that just throws an exception), since even a function with no return value is valid in a boolean statement, but it seems like a bad idea to create a function like that just so you can do clever things with boolean statements.

like image 174
Brendan Long Avatar answered Sep 18 '22 23:09

Brendan Long