Posted by & filed under PHP.

Here’s an autoloader class I came up with for one of my framework-free PHP projects. Autoloading is a way to let PHP know how you’ve architected your class file locations hierarchy by supplying it with a function to run. This function will handle the including of the class file. This is awesome because we don’t need to hard code every file include. Also, files are only loaded when needed, which makes code execution quicker.

For a more up-to-date guide on PHP development checkout Modern PHP: New Features and Good Practices. It contains much more detailed information than in this blog post.

You’ll want to put your class files into a folder named Classes, which is in the same directory as the entry point into your PHP application. If classes use namespaces, the namespaces will be converted into the directory structure. Unlike a lot of other auto-loaders, underscores will not be converted into directory structures (it’s tricky to do PHP < 5.3 pseudo namespaces along with PHP >= 5.3 real namespaces).

<?php
class Autoloader {
    static public function loader($className) {
        $filename = "Classes/" . str_replace("\\", '/', $className) . ".php";
        if (file_exists($filename)) {
            include($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('Autoloader::loader');

You’ll want to place the following code into your main PHP script (entry point):

require_once("Classes/Autoloader.php");

Here’s an example directory layout:

index.php
Classes/
  Autoloader.php
  ClassA.php - class ClassA {}
  ClassB.php - class ClassB {}
  Business/
    ClassC.php - namespace Business classC {}
    Deeper/
      ClassD.php - namespace BusinessDeeper classD {}

Thomas Hunter II

Thomas is a published author and a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.

Tags:

  • Marcio

    Great tutorial! Thank you!

  • Is it possible to use “use” inside the namespace classes? Please explain?

  • Yura

    Thanks, simple and effective. Only one remark – backslash should be escaped

    class Autoloader {
    static public function loader($className) {
    $filename = “Classes/” . str_replace(‘\\’, ‘/’, $className) . “.php”;
    if (file_exists($filename)) {
    include($filename);
    if (class_exists($className)) {
    return TRUE;
    }
    }
    return FALSE;
    }
    }
    spl_autoload_register(‘Autoloader::loader’);