I am learning advanced PHP standards and trying to implement new and useful methods. Earlier I was using __autoload just to escape including multiple files on each page, but recently I have seen a tip on __autoload manual
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.
but I really can’t figure out how to implement spl_autoload and spl_autoload_register
spl_autoload_register()allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.So for example:
In the example above, "MyClass" is the name of the class that you are trying to instantiate, PHP passes this name as a string to
spl_autoload_register(), which allows you to pick up the variable and use it to "include" the appropriate class/file. As a result you don’t specifically need to include that class via an include/require statement…Just simply call the class you want to instantiate like in the example above, and since you registered a function (via
spl_autoload_register()) of your own that will figure out where all your class are located, PHP will use that function.The benefit of using
spl_autoload_register()is that unlike__autoload()you don’t need to implement an autoload function in every file that you create.spl_autoload_register()also allows you to register multiple autoload functions to speed up autoloading and make it even easier.Example:
With regards to spl_autoload, the manual states:
In more practical terms, if all your files are located in a single directory and your application uses not only .php files, but custom configuration files with .inc extensions for example, then one strategy you could use would be to add your directory containing all files to PHP’s include path (via
set_include_path()).And since you require your configuration files as well, you would use
spl_autoload_extensions()to list the extensions that you want PHP to look for.Example:
Since spl_autoload is the default implementation of the
__autoload()magic method, PHP will call spl_autoload when you try and instantiate a new class.