8

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"?

Community
  • 1
  • 1
TheFrack
  • 2,823
  • 7
  • 28
  • 47

2 Answers2

12

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.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
  • 2
    Actually, it doesn't work because `throw`, just like `echo`, `include`, etc. is a language construct rather than a function :) – Ja͢ck Oct 05 '12 at 17:13
  • Yeah I was trying to avoid the IF statement. So useful, thanks guys. – TheFrack Oct 05 '12 at 17:15
3

The similar question has been asked before.

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

the reason

bar() or throw new Exception();

is illegal, is because

(boolean)throw new Exception();

is also illegal. In essence, the process of throwing an exception doesn't generate a return value for the operator to check.

Community
  • 1
  • 1
Roger Ng
  • 771
  • 11
  • 28