PHP Autoload Class From Namespace I wrote this function to be passed as a param in spl_autoload_register(). It autoloads PHP classes from their respective directories using their namespace, named the same as path. I am not sure if there would be any easier way but this is quite simple and does what it needs to.

spl_autoload_register(function($class) {
    $ns = explode('\\', strtolower($class));
    $class = array_pop($ns);
    $ns = implode('\\', $ns) . '\\';
    require_once __DIR__ . '\\' .  $ns . 'class.' . $class . '.php';
});


Thoughts on this? Is there an easier way?
If your namespaces match your directory structure you would not need to fetch the class name. You could just append it to the base path and append the .php file extension.

I would argue the class. file prefix is unnecessary. I think of such prefixes from a time when namespaces was not available. If you are concerned with the ease of locating correct files I can recommend the following method. I have used for several projects and are quite happy with it. 

classes/
    interfaces/
        interfaceName.php
    abstracts/
    traits/
    class.php
    anotherclass.php


I hope you get the idea. If you follow this you can use this.

spl_autoload_register(function($class) {

    $filename = __DIR__ . '\\' . $class . '.php';

    if(!file_exists($filename)) {
        return false; // End autoloader function and skip to the next if available.
    }

    include $filename;
    return true; // End autoloader successfully.

});


This is pretty much it. You should of course check that __DIR__ equals your base path. If you store your base path inside a variable and you are using a closure as callback, you can inject the path into the closure using this:

$path = 'This is your base path.';

spl_autoload_register(function($class) use ($path) {...});


If your file system uses forward-slashes (for some reason), you could wrap the $class variable in a str_replace() function call.

$class = str_replace('\\', '/', $class);


Happy coding!