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

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

    A solution I found that can replace "or die()" everywhere is to wrap the throw with a anonymous function that gets called immediately by call_user_func:

    call_user_func(function(){
        throw new Exception("ERROR");
    });
    

    You can see that it works by executing this on a dummy script:

    false or call_user_func(function(){throw new Exception("ERROR");});
    

提交回复
热议问题