spl_autoload_register: Always Throws

Since PHP 8.0, spl_autoload_register() can throw exceptions regardless of the second argument. Additionally, passing true as the second argument will emit a notice.

Here is an example attempting to register two autoloaders, but only one of them has a declared function:

function my_autoloader_1($class) { }

foreach (array('my_autoloader_1', 'my_autoloader_2') as $autoloader) {
    spl_autoload_register($autoloader, false);

Prior to PHP 8.0, the code above would silently ignore the missing my_autoloader_2 due to the false argument. See execution result.

Since PHP 8.0, it will instead emit a notice for my_autoloader_1, because the second argument is false, and throw a TypeError for my_autoloader_2.


Use true for the second argument to avoid the notice. After that, you need to deal with the potential exception.

If possible, always ensure that the first argument is a valid callable, which is largely a manual process:

function my_autoloader_1($class) { }
spl_autoload_register('my_autoloader_1', true);

If the previous option is not practical, you can emulate the old behavior by silencing the exception using try/catch:

function my_autoloader1($class) { }

foreach (array('my_autoloader_1', 'my_autoloader_2') as $autoloader) {
    try {
        spl_autoload_register($autoloader, true);
    catch (TypeError $e) {}
    catch (LogicException $e) {}

You can choose TypeError for support on PHP 8.0 and higher, LogicException for support on PHP 7.4 and lower, or keep both to allow this code to be compatible across the most PHP versions. See execution result. Having both might be desirable in case you want to upgrade your code over time instead of all at once.

Errors or Warnings

See Also