PHP: dynamic or program blocks

I have a situation where it would be nice to have a catch block where the type of Exception is determined at runtime. This will work something like this:

$someClassName = determineExceptionClass();

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

Is it possible?

+5
source share
1 answer

This does not work as far as I know. You can simulate this functionality using the control statement as follows:

$someClass = 'SomeException';

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

All Articles