Since version 5, you can autoload classes in PHP. Autoloading functionality is part of the SPL (Standard PHP Library), a set of classes and interfaces that are meant to solve standard problems. In this article, I will show you what autoloading is all about and how you can benefit from it.

As a best-practice, many developers create one class per file using the same naming conventions. Here I will assume that classes are using the convention ClassName.class.php.

Your Code Before

<?php
    include "User.class.php";
    include "Database.class.php";
    include "FileUploader.class.php";
    include "Foo.class.php";
    include "Bar.class.php";
?>

Your Code After

<?php
    include "Autoload.class.php";
?>

What is autoloading?

Even a PHP site or application of minor complexity will inevitably have a list of includes at the top of each script. This ends up becoming a cumbersome clutter, especially to those developers who are properly creating their classes in individual files.

In PHP 5, you are no longer required to use all these includes/requires. You can now define a method called __autoload() that allows PHP to load classes as needed, even though they have not been defined. This allows you to simplify your scripts with a single, simple method. This is the main benefit of autoloading.

Solid Tip: Note that this method name starts with two underscores.

Simply make yourself an Autoload.class.php file with this basic function and include it in your scripts:

function __autoload($name) {
    include $name.".class.php";
}

The Example

<?php
    include "Autoload.class.php";
 
    // now you can use your classes without all the includes
    $myuser = new User();
    $mycxn = new Database();
    $myfile = new FileUploader();
    $myfoo = new Foo();
    $mybar = new Bar();
?>

Without an __autoload() function , calling a class that wasn’t defined would result in a Fatal Error. When it is present, PHP will automatically run it whenever you instantiate a class that is not defined yet.

This __autoload() example is about as basic as it gets. There are additional SPL autoload methods that expand and enhance this functionality.

Advanced or curious users can learn more about these SPL methods at PHP.net.