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

后端 未结 7 1776
萌比男神i
萌比男神i 2020-12-06 04:30

Everyone here should know the \'or\' statemens, usually glued to an die() command:

$foo = bar() or die(\'Error: bar function return false.\');
7条回答
  •  情歌与酒
    2020-12-06 05:17

    I think you want to use something like the last structure, although there's really no point in using exceptions for that:

    $foo = bar();
    if(!$foo){
        echo 'We have a problem in here';
    }
    

    Per comment - I don't think you can do that in a single line (i.e. without the if(!$foo) check), and I agree that the exception throwing method is pretty horrible. Personally, I prefer the explicitness of:

    $foo = bar();
    if(!$foo){
        throw new Exception('We have a problem in here');
    }
    

    but that's a personal preference. If you want the single-line thing, I think you'll have to go with your exception-throwing function option.

    I guess this limitation is probably down to PHP's dynamic-typing stuff, it can cast the results of a function call to a conditional, but not the results of a throw.

提交回复
热议问题