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 passionate about technology and building products. A web design business created while attending college slowly evolved into a brick and mortar on Main St. of his small Midwestern hometown. His desire for fame and fortune led to the co-founding of a Y Combinator startup and a life in California.

Tags:

Hey there! I'm currently writing a book on Microservices which I expect to release in early 2017. If you're interested in getting updates please signup here. More info about the Book
  • 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’);