Skip to content

Instantly share code, notes, and snippets.

Last active January 22, 2024 14:45
  • Star 31 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save adriengibrat/4761717 to your computer and use it in GitHub Desktop.
Extreme minification of shortest possible PSR-0 compliant autoloader, 5 lines !
//set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__); // optional
spl_autoload_register(function ($class) {
$file = preg_replace('#\\\|_(?!.+\\\)#','/', $class) . '.php';
if (stream_resolve_include_path($file))
require $file;
Copy link

Yeah, i copied the wrong code i think, it's corrected ;)

is resolved as

About return : I thought returning true could stop the spl autoload stack iteration earlier, but there is no need to do so (spl check if class exists after callink each callback in the stack).

@include (Silent warning) is better than require (Fatal error) because final user could use multiple autolader (with different logic to resolve path) , and we don't know where our autoloader will be in the stack!

Copy link

adriengibrat commented Nov 15, 2013

@include was lame... Now i check if the file can be included, then require it ;)

Copy link

Why not use require_once? Or does spl_autoload_register automatically prevent loading files multiple times?

Copy link

adriengibrat commented Feb 8, 2014

Yes, autoloading happens only if the class definition is not yet included. But may be require_once is safer ;)

Copy link

This regex is reliable?
Some tests indicate an error in this part "(?!".

Copy link

makryl commented Sep 15, 2014

For the perfect, please add braces to if statement :))
"The body of each structure MUST be enclosed by braces." (c) PSR-2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment