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

后端 未结 7 1774
萌比男神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:25

    I've simply defined the function toss for this.

    function toss(Exception $exception): void
    {
        throw $exception;
    }
    

    Because the file/line/stack information is captured when the exception is constructed (new) not thrown (throw) this doesn't interfere with the call stack.

    So you can just do this.

    something() or toss(new Exception('something failed'));
    
    0 讨论(0)
提交回复
热议问题