athene athene - 1 year ago 101
PHP Question

autoload vs include or require in php

I am currently going through autoloading and l realize that autoloading may just be the same with require or include and I have come to the conclusion that perhaps there could be an advantage for using autoloading instead of require or include.
What is the advantage of using autoload instead of require or include to use a class in a php file?

Answer Source

When you are working in a file, you might have to require in other files at the top in order to use their functionalities.

Depending on the requirement, that list can get very long. And doing this in every file is tedious,unclean and can be avoided.

Hence, autoload your files.

For example, you can keep all your classes under one folder named classes. Then make a bootstrap file where you can write the autoloader:

spl_autoload_register(function ($class) {
    require_once 'classes/' . $class . '.php';

To make this work, all you have to do is keep the file name and class name the same.

Henceforth you need to require only this bootstrap file and all your classes will be autoloaded.