Search code examples
phpautoloadspl

multiple spl_autoload_register


what is/are the benefit(s) of having multiple spl_autoload_register

example:

spl_autoload_register('autoload_systems');
spl_autoload_register('autoload_thirdparties');
spl_autoload_register('autoload_services');

vs:

using one

spl_autoload_register('autoload'); or __autoload();

and then do the logic inside the function.

eg:
$ftp = new systems_ftp();
$services = new services_cron_email();

Solution

  • If you have one __autoload() and you include a third party library which also had one, it would be clobbered.

    Registering multiple autoloads with spl_autoload_register() ensures you can have your code dropped in with existing code (think libraries, etc) without clobbering or shadowing of existing/future autoloads.

    In addition, the PHP manual states...

    spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.