Autoloading Classes

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.

images/articles/php/auloading-classes.jpg

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. It takes one parameter, which is the name of the class or interface that PHP is looking for.

function __autoload($classname) 
{
$lastSlash = strpos($classname, '\\') + 1;
$classname = substr($classname, $lastSlash);
$directory = str_replace('\\', '/', $classname);
$filename = __DIR__ . '/' . $directory . '.php';
require_once($filename);
}

The 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.

A good coding practice to follow when writing object-oriented applications is to have one source file for every class definition, and to name the file according to the class name. Following this convention, the __autoload function is able to load the class - provided that it is in the same folder as the script file that needed it.