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”?
Do it the less “clever” way:
In case you’re wondering why
or throw new Exception()doesn’t work, it’s because you’re relying on the short-circuiting of theoroperator: 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
throwsince it’s an expression that doesn’t return a boolean value (or any value at all), sooring 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.