Bas
Bas

Reputation: 2210

Using get_class in try - catch block

Questions

My own try

Whenever using the get_class, it returns the class name as a string. When I tried to instantiate it like this:

$classWhereExceptionObjectIsStored = new classWhereExceptionObjectIsStored();

try {
   //Some code

} catch(get_class($classWhereExceptionObjectIsStored->getExceptionObject $e)) {
   //Do stuff with the exception
}

It didnt work.

The class:

class classWhereExceptionObjectIsStored
{

    public function getExceptionObject($message) {
        return new LogicException($message); //For example
    }
}

Second try

$class = get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'));

try {
   //Some code

} catch($class $e)) {
   //Do stuff with the exception
}

Upvotes: 0

Views: 333

Answers (1)

Sherlock
Sherlock

Reputation: 7597

get_class returns just the name of the class, that's the use of that function. You can instantiate a class dynamically by doing:

new $class();

Which in your case would probably have to result in something like:

new get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'));

This doesn't work in a catch block. That's because you don't instantiate anything in a catch block - the only thing you specify there is the exception class you're expecting to get.

An alternative would be to catch all exceptions:

catch(Exception $e){}

And then within that catch use the PHP function is_a to check if the thrown exception is of the type you're expecting, like so:

if(is_a($e, get_class($classWhereExceptionObjectIsStored->getExceptionInstance('hi!'))){}

However, I truly question your motives. I can't think of any use case where this would add functionality, readability, scalability or usability.

Upvotes: 1

Related Questions