In order to use a class, you need to include the file that defines it. Autoloading is a PHP feature that allows your program to search and load files automatically given some set of predefined rules. Each time you reference a class that PHP does not know about, it will ask the autoloader.
If the autoloader can figure out which file that class is in, it will load it, and the execution of the program will continue as normal. If it does not, PHP will stop the execution.
Autoloader is a PHP function that gets a class name as a parameter, and it is expected to load a file. There are two ways of implementing an autoloader: either by using the __autoload function or the spl_autoload_register one.
Using the __autoload Function
Defining a function named __autoload tells PHP that the function is the autoloader that it must use.
$lastSlash = strpos($classname, '\\') + 1;
$classname = substr($classname, $lastSlash);
$directory = str_replace('\\', '/', $classname);
$filename = __DIR__ . '/' . $directory . '.php';
Our intention is to keep all PHP files in src, that is, the source. The function tries to find the first occurrence of the backslash \ with strpos, and then extracts from that position until the end with substr.
Using the spl_autoload_register Function