Algorithmic Advent: 08 – Namespace autoloading

Published on 8 Dec 2010. Tagged with php, algorithmicadvent.

If you're not using PHP namespaces or if you're not using autoloading, now would be a good time to start. Loading dependencies won't get easier that that.

/* This code should be placed in your index file */

// Set library path (put your classes in this directory)
$libraryPath = realpath('./library');

// Add to include path
set_include_path($libraryPath . PATH_SEPARATOR . get_include_path());

// Autoloader
spl_autoload_register(function ($class) {
    require_once str_replace('\\', '/', $class) . '.php';

use Demo\Foo,

$f = new Foo(); // The files './library/Demo/Foo.php' and
$b = new Bar(); // './library/Some/Other/Name/Space/Bar.php'
                // will be autoloaded