0

I am finding that when Zend tries to auto load a file which doesn't exist, it throws an error which I cannot catch in a try/catch block. This happens when I use class_exists too. I have fixed the problem by hacking zend:

if ($once) {
    if (!@include_once ($filename)) {
        throw new Exception("Failed to include $filename");
    }
    // include_once $filename;
}
else {
    if (!@include ($filename)) {
        throw new Exception("Failed to include $filename");
    }
    // include $filename;
}

The commented out lines are zend's originals. Now I can catch the exception thrown when a file cannot be included. Can anybody suggest a cleaner way to do this which doesn't involve hacking zend?

I am on Zend version 1.11.10, and the code in question is Zend_Loader line 146.

Thanks.

George Brighton
  • 5,131
  • 9
  • 27
  • 36
xanld
  • 977
  • 1
  • 11
  • 22

2 Answers2

1

instead of using include or include_once try using Zend_Loader::loadClass()

Here is the API: Zend_Loader::loadClass($class, $dirs)

An example:

Zend_Loader::loadClass('Container_Tree',
    array(
        '/home/production/mylib',
        '/home/production/myapp'
    )
);

Now the blurb on how it works:

The string specifying the class is converted to a relative path by substituting underscores with directory separators for your OS, and appending '.php'. In the example above, *'Container_Tree'* becomes 'Container\Tree.php' on Windows.

If $dirs is a string or an array, *Zend_Loader::loadClass()* searches the directories in the order supplied. The first matching file is loaded. If the file does not exist in the specified $dirs, then the include_path for the PHP environment is searched.

If the file is not found or the class does not exist after the load, *Zend_Loader::loadClass()* throws a Zend_Exception.

This should allow you to use a try/catch block for any non-existent classes. Zend_Loader::loadFile() also has similar functionality.

RockyFord
  • 8,529
  • 1
  • 15
  • 21
0

Don't try and autoload classes that don't exist. If for some reason the class you're trying to autoload may or may not be there, wrap that part of code with a class_exists() call.

I can't think of any reason why you would want class_exists() to throw an exception on failure since it's sole purpose is to allow you to check for the existence of classes.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69