Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 947
FallenAvatar Avatar asked Jun 09 '11 21:06

FallenAvatar


People also ask

Which function is used to check if class is exist or not?

The class_exists() function in PHP checks if the class has been defined. It returns TRUE if class is a defined class, else it returns FALSE.


1 Answers

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
}
like image 159
Dan Soap Avatar answered Oct 19 '22 23:10

Dan Soap