One thing: spl_autoload_register does not throw exceptions. So there simply is no need to wrap that call into a try/catch - it won't ever happen to do anything! The only thing it returns is a boolean: true on success, or false on failure, which will probably only happen if you try to register a function that does not exist, or you pass something that is not callable.
The second thing: Be a nice citizen, do not cancel the autoloading process in your own function! Should you or anyone else use your autoloader together with a second one, like it would be the case if any other library with it's own autoloader is in use, then ALL these autoloaders might get called with the classname, and ONLY the one responsible for that kind of class must load it.
So if your autoloader cannot load the class, it must do nothing. Not throw any exception, not trigger an error. PHP will call another autoloading function after yours if it is defined, and if not, you'll get that nasty "Fatal error: Class 'Foobar\InexistentClass' not found". And this is a good thing because you were using a class that couldn't be loaded - either because of a typo, or an error in the autoloader, or some other reason.
One more thing: You really don't have to use require_once()
for the loading. The autoloader will only be triggered ONCE to load a class. require_once()
has a performance penalty because PHP must check if the file has been loaded before - and this check will NEVER prevent a second loading, because the autoloader will never be called a second time for an already known class.
How to prevent fatal errors if classes cannot be loaded? Impossible! In theory the autoloader could be coded to run eval()
tp create the required class as an empty code fragment without any functions, or maybe even with designated __set, __get and __call magic functions that would intercept any usage, but what would that help? Your code required a class that does something, and that class cannot be found! This really IS a fatal error, and should be resolved, not hidden.
Last suggestion: Go with the PSR-0 autoloading standard. There are plenty of autoloaders already existing, and it is the defacto standard for any decent library. It will make everbodys life so much easier.
Update:
You can install your own error handler that is executed on PHP errors: set_error_handler() But this won't help with fatal errors.