1

I'm using spl_autoload_register to load certain classes when they are needed, but how can I catch the error when the class is not found by my autoload method?

Right now the only solution I see is to display a cute error message in my autoload callback and stop the application so that error never gets to show.

But I don't want to stop the application. I want to continue and skip the instantiation of the missing class I needed (in my specific case, they are not strictly required for the app to continue to run)

bogatyrjov
  • 5,317
  • 9
  • 37
  • 61
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 1
    Similar post to [this one](http://stackoverflow.com/questions/1579080/throwing-exceptions-in-an-spl-autoloader). – Alon Adler Feb 09 '12 at 20:54

2 Answers2

10

Use class_exists() before loading and handle the result appropriately. If it exists, instantiate as per usual. If it doesn't, skip the instantiation.

kba
  • 19,333
  • 5
  • 62
  • 89
  • thanks! it works :D I feel pretty stupid for not thinking of trying that – Alex Feb 09 '12 at 21:00
  • Having to use `class_exists` before every instantiation is a pain, and using it triggers the loader anyway. Might as well just use it in the loader. – Leigh Feb 09 '12 at 21:00
  • @Leigh Yes, it definitely should be implemented in the autoloader. – kba Feb 09 '12 at 21:12
  • @KristianAntonsen: Your "before loading" confused me, if you do `class_exists` in an autoloader, before loading (the file?), infinite loop ensues (or we hit a max recursion depth somewhere - not sure)? – Leigh Feb 09 '12 at 21:15
2

In order to mute the error you could dynamically create the missing classes when they are called, though I do not recommend such approach.

The following code worked for me:

function __autoload($name) {
eval("class {$name} {}");
}

echo 'pass 1';
$a = new a();
echo 'pass 2';
Tony Bogdanov
  • 7,436
  • 10
  • 49
  • 80