I have a project which registers an autoloader using spl_autoload_register() that falls back to running include_once(). If the file being loaded contains syntax errors, I want want to see errors logged normally, based on the current error reporting mode. However, if my code includes a call to class_exists('NoneSuch'), I don’t want to see a warning. I’m sure I’m missing something, but can’t work out how to achieve that.
Here’s a MWE using a file called lib/Foo.pm that contains a syntax error:
<?php clsas Foo { }
And here's the main file:
#!/usr/bin/env php
<?php error_reporting(E_ALL);
spl_autoload_register(function ($class) {
$libdir = 'lib' . DIRECTORY_SEPARATOR;
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
include_once("$libdir$path.php");
});
# This should not log a warning
class_exists('NoneSuch');
# This should report the syntax error in Foo.pm
new Foo;
I know I can prefix the call to class_exists() with an @ to suppress warnings – that would be ideal – but many of these calls are in third-party code that I cannot edit. Likewise, I know I can disable warnings with error_reporting(E_ALL & ~E_WARNINGS), but many of the warnings PHP gives are useful. If I prefix the include_once() with an @, then I lose the syntax errors in Foo.pm too.
I can’t easily wrap the include_once() in an if (file_exists("...")) {} because that doesn’t respect include paths, and I can’t easily use the default spl_autoload() function because that won’t know about by $libdir variable. I don't particularly want to append $libdir to the include path, because I don't want these files to be loadable by include() other than via the autoloader because the actual autoloader does quite a bit more for debugging, profiling and making legacy class aliases that isn't included in this MWE, and I don't want these being accidentally bypassed.
Is there any way of telling whether the autoloader function is being called by a class_exists() call?