How to detect if a class does not exist without triggering an error

FallenAvatar picture FallenAvatar · Jun 9, 2011 · Viewed 17.7k times · Source

I have run into an interesting dilema. In a DataMapper class, I am generating a class name to be used for returned rows from a database.

The thing is, all of my classes are autoloaded, and can come from many places (library, application/models, etc.) and I wanted to check if the class name generated actually exists. Now, one would think that:

try
{
    $test = new $className();
}
catch(Exception $ex)
{
    // Class could not be loaded
}

But of course, php errors (instead of throwing an exception) saying the class could not be found... Not very helpful. Short of rewriting the autoloader in Zend_Loader to search all directories to see if the class could be loaded, is there anyway to accomplish this?

For anyone wondering why I would need to do this instead of just letting the Class Not Found error show up, if the class isn't found, I want to generate a class in a pre-determined location to make my life easy as this project goes along.

Thanks in advance!

Amy

P.S. Let me know if you guys need any more info.

Answer

Dan Soap picture Dan Soap · Jun 9, 2011

PHP's function class_exists() has a flag to trigger the autoloader if the class should not be loaded yet:

http://www.php.net/class_exists

So you simply write

if (!class_exists($className)) {
    // generate the class here
}