multiple spl_autoload_register multiple spl_autoload_register php php

multiple spl_autoload_register


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.


I guess no need to add multiple but it's on your logic.The way spl_autoload_register works is awesome.Suppose one have 3rd parties directories and that is usually manages through namespace which also represents their path.Consider this simple class as autoloader class

 class MyAutoLoader {     public function __construct()     {         spl_autoload_register( array($this, 'load') );     }     function load( $class )     {         $filepath = 'classes/'.$class.'.php';         require_once( $filepath);     } }

Then in index file include this loader file and create instance of this class:

$autoload = new MyAutoLoader();

Now you can directly create the instances of classes.Suppose we have 'Person' class in directory classes\QMS\SERVICES\Person.php and same path is the namespace of that class

$person = new QMS\SERVICES\Person();

Now when when you will use new it will check if this class exists and value as a string will be passes to 'load' function of class 'MyAutoLoader'. and there it will get included. Or you can change the function 'load' to fix the path of your class files put your if conditions or whatever need to b done to fix the paths.