PHP Autoload
In large PHP applications you typically see a “classes” directory that only contains classes which are used throughout the application (database, session management, forms etc..). A problem quickly appears: Everytime you wanted to use one of the classes, you would be forced to include() it at the top of the page. __autoload() solves this by automatically including the definition file when a class is called.
Example
We have a simple application with the index.php file in the root directory and a directory called classes that contains numerous classes.
classes/time.class.php
class time
{
function fn1()
{
echo 'hello world';
}
}
The code below shows what we’d need to do if we didn’t have autoload. While that code doesn’t seem so bad, imagine writing includes on each of your 30-40 files. It would get messy and very hard to maintain. Another option would be to have a single file that all of your classes are included in, there include that one file in each of your functional scripts but you could expect a performance loss as every one of your classes would be included on the page – even if it wasn’t needed.
index.php
include('classes/time.class.php');
$time = new time();
$time->fn1();
//Returns hello world
The __autoload() function accepts one parameter – the name of the class that is being instantiated. We pass this so we know what file to include.
index.php revised
function __autoload($class_name)
{
include('classes/' . $class_name . '.class.php');
}
$time = new time();
$time->fn1();
//Returns hello world
A More Complex Example
Large projects and frameworks often have classes split up into groups – extensions, modules and core components. When instantiating a new class, we don’t want to have to declare what group it belongs to. We can build this right into our autoload function, and also check if the file/class exists.
function __autoload($class)
{
if(file_exists('core/' . $class . '.class.php'))
{
include('core/' . $class . '.class.php');
}
if(file_exists('extensions/' . $class . '.class.php'))
{
include('extensions/' . $class . '.class.php');
}
if(file_exists('modules/' . $class . '.class.php'))
{
include('modules/' . $class . '.class.php');
}
}

