Simple PHP Namespace Friendly Autoloader Class

Support this website by purchasing prints of my photographs! Check them out here.

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.

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

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

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


Here's an example directory layout:

  ClassA.php - class ClassA {}
  ClassB.php - class ClassB {}
    ClassC.php - namespace Business classC {}
      ClassD.php - namespace BusinessDeeper classD {}
Tags: #php
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.