18

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.

FallenAvatar
  • 4,079
  • 1
  • 21
  • 24

1 Answers1

28

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
}
Dan Soap
  • 10,114
  • 1
  • 40
  • 49