David Jones

Autoload with namespaces

If I am using version 5.3 or above of PHP I will use namespaces. This means I need to use a autoloader that can process namespaced class names without throwing any errors. Here is what I came up with.

spl_autoload_register(function($class) {
    $file = strtolower(PATH.str_replace(array('\\', '-'), array('/', '_'), ltrim(strtolower($class), '\\')).'.php');

    if(is_file($file)) {
        include $file;
    }
});

This is a nice and simple custom autoloader function that breaks up the namespaced class name and adds it to the PATH constant, that is the path of the current environment, and the file extension on the end that will always be .php.