An example of a general-purpose implementation that includes the optional functionality of allowing multiple base directories for a single namespace prefix.
Given a foo-bar package of classes in the file system at the following paths ...
/path/to/packages/foo-bar/
    src/
        Baz.php             # Foo\Bar\Baz
        Qux/
            Quux.php        # Foo\Bar\Qux\Quux
    tests/
        BazTest.php         # Foo\Bar\BazTest
        Qux/
            QuuxTest.php    # Foo\Bar\Qux\QuuxTest
... add the path to the class files for the \Foo\Bar\ namespace prefix as follows:
 <?php
 // instantiate the loader
 $loader = new \Example\Psr4AutoloaderClass;
 // register the autoloader
 $loader->register();
 // register the base directories for the namespace prefix
 $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/src');
 $loader->addNamespace('Foo\Bar', '/path/to/packages/foo-bar/tests');
The following line would cause the autoloader to attempt to load the \Foo\Bar\Qux\Quux class from /path/to/packages/foo-bar/src/Qux/Quux.php:
 <?php
 new \Foo\Bar\Qux\Quux;
The following line would cause the autoloader to attempt to load the \Foo\Bar\Qux\QuuxTest class from /path/to/packages/foo-bar/tests/Qux/QuuxTest.php:
 <?php
 new \Foo\Bar\Qux\QuuxTest;
                    | package | 
                                                                                    
                                                                                 LightMVC/ASCMVC  | 
                                
|---|
addNamespace(string $prefix, string $base_dir, boolean $prepend = false) : void
stringThe namespace prefix.
stringA base directory for class files in the namespace.
booleanIf true, prepend the base directory to the stack instead of appending it; this causes it to be searched first rather than last.
loadClass(string $class) : mixed
stringThe fully-qualified class name.
mixedThe mapped file name on success, or boolean false on failure.
loadMappedFile(string $prefix, string $relative_class) : mixed
stringThe namespace prefix.
stringThe relative class name.
mixedBoolean false if no mapped file can be loaded, or the name of the mapped file that was loaded.
register() : void
requireFile(string $file) : boolean
stringThe file to require.
booleanTrue if the file exists, false if not.
prefixes : array
| var | 
|---|
array