PHP – most lightweight psr-0 compliant autoloader

You ask extremely lightweight, let’s do so 😉

Timothy Boronczyk wrote a nice minimal SPL autoloader : http://zaemis.blogspot.fr/2012/05/writing-minimal-psr-0-autoloader.html

I condensed the code like this:

function autoload1( $class ) {
    preg_match('/^(.+)?([^\\\\]+)$/U', ltrim( $class, '\\' ), $match ) );
    require str_replace( '\\', "https://stackoverflow.com/", $match[ 1 ] )
        . str_replace( [ '\\', '_' ], "https://stackoverflow.com/", $match[ 2 ] )
        . '.php';
}

Then compare (minified versions of) this [autoload3] with short @Alix Axel code [autoload4] :

function autoload3($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\',"https://stackoverflow.com/",$m[1]).str_replace(['\\','_'],"https://stackoverflow.com/",$m[2]).'.php';}
function autoload4($c){require (($n=strrpos($c=ltrim($c,'\\'),'\\'))!==false?str_replace('\\',"https://stackoverflow.com/",substr($c,0,++$n)):null).str_replace('_',"https://stackoverflow.com/",substr($c,$n)).'.php';}

autoload3 is the shortest !

Let’s use stable & extremely lightweight (175b !) autoloader file :

<?php spl_autoload_register(function ($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\',"https://stackoverflow.com/",$m[1]).str_replace(['\\','_'],"https://stackoverflow.com/",$m[2]).'.php';});

Maybe i’m crazy but you Asked for extreme, no?

EDIT: Thanks to Alix Axel, i’ve shorten the code (only 100b !) and used include instead of require in case you have various autoloading strategy for old libs (and then various autoloader in spl autoload stack…).

<?php spl_autoload_register(function($c){@include preg_replace('#\\\|_(?!.+\\\)#',"https://stackoverflow.com/",$c).'.php';});

If you want to make it shorter / better, please use this gist.

Leave a Comment