PHP: Dynamic or Programmatic Catch Blocks

拟墨画扇 提交于 2019-12-19 06:57:31

问题


I have a situation where it would be nice to be able to have a catch block where the type of the Exception is determined at run time. It would work something like this:

$someClassName = determineExceptionClass();

try {
  $attempt->something();
} catch ($someClassName $e) {
  echo 'Dynamic Exception';
} catch (Exception $e) {
  echo 'Default Exception';
}

Is this at all possible?


回答1:


That doesn't work as far as I'm aware. You could mimic that functionality with a control statement like this:

$someClass = 'SomeException';

try
{
    $some->thing();
}
catch (Exception $e)
{
    switch (get_class($e))
    {
        case $someClass:
            echo 'Dynamic exception.';
            break;
        default:
            echo 'Normal exception.';
    }
}


来源:https://stackoverflow.com/questions/11925020/php-dynamic-or-programmatic-catch-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!