Simple PHP Namespace Friendly Autoloader Class

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

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 is the author of Advanced Microservices and is 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.