views:

22

answers:

1

Scenario: I have a class that extends another class, yet the parent class is undefined (for whatever reason). I am trying to get a ReflectionClass of the child class. When I do this, I get a Class Not Found exception on the parent class. However, I cannot catch this exception. What am I doing wrong?

For example...

<?php
class Foo extends Bar { }

try
{
    $class = new ReflectionClass('Foo');
    echo 'I\'ve reflected "Foo" successfully!';
}
catch (Exception $e)
{
    echo 'My exception handler';
}

The result of the above code is a printout of the class 'Bar' not found exception. Why is my catch statement not picking up the exception?

thanks, Kyle

A: 

That's because the exception occurred on this line and not on the lines after try:

class Foo extends Bar { }

I tried it, putting the class declaration on a try-catch won't work too. Make sure Bar is included first.

Shiki
Is there anyway to catch an exception when including the file with the `Foo` class declaration? This is for generating class documentation, so being valid and runnable isn't necessary, just being able to recognize when the class is invalid (ie, parent undefined). Is there any way to do this?
vimofthevine
It's a little bit tricky to handle Fatal errors. [See here](http://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error). If it were me, I would probably open and parse the included file (i.e. Foo.php) as a text file and regex my way through the code to find `extends Bar` and check if it exists with [class_exists](http://php.net/manual/en/function.class-exists.php).
Shiki