你要求非常轻量,让我们这样做吧;)
Timothy Boronczyk 写了一个很好的最小 SPL 自动加载器:http://zaemis.blogspot.fr/2012/05/writing-minimal-psr-0-autoloader.html http://zaemis.blogspot.fr/2012/05/writing-minimal-psr-0-autoloader.html
我将代码压缩如下:
function autoload1( $class ) {
preg_match('/^(.+)?([^\\\\]+)$/U', ltrim( $class, '\\' ), $match ) );
require str_replace( '\\', '/', $match[ 1 ] )
. str_replace( [ '\\', '_' ], '/', $match[ 2 ] )
. '.php';
}
然后将此 [autoload3] 与(缩小版本)进行比较短@Alix Axel 代码 https://stackoverflow.com/a/14416954/1154106[自动加载4]:
function autoload3($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\','/',$m[1]).str_replace(['\\','_'],'/',$m[2]).'.php';}
function autoload4($c){require (($n=strrpos($c=ltrim($c,'\\'),'\\'))!==false?str_replace('\\','/',substr($c,0,++$n)):null).str_replace('_','/',substr($c,$n)).'.php';}
autoload3是最短的!
让我们使用稳定且极其轻量级(175b!)的自动加载文件:
<?php spl_autoload_register(function ($c){preg_match('/^(.+)?([^\\\\]+)$/U',ltrim($c,'\\'),$m);require str_replace('\\','/',$m[1]).str_replace(['\\','_'],'/',$m[2]).'.php';});
也许我疯了,但你要求极端,不是吗?
EDIT:感谢 Alix Axel,我缩短了代码(仅 100b!),并使用 include 而不是 require,以防您对旧库有各种自动加载策略(然后是 spl 自动加载堆栈中的各种自动加载器...)。
<?php spl_autoload_register(function($c){@include preg_replace('#\\\|_(?!.+\\\)#','/',$c).'.php';});
如果你想让它更短/更好,请使用这个gist https://gist.github.com/adriengibrat/4761717.