Using 有一个陷阱,虽然它是迄今为止最快的方法,但它也希望你的所有文件名都是小写的。
spl_autoload_extensions(".php");
spl_autoload_register();
例如:
包含 SomeSuperClass 类的文件需要命名为 somesuperclass.php,如果您的文件命名为 SomeSuperClass.php 但在 Windows 下没有问题,则使用 Linux 等区分大小写的文件系统时这是一个问题。
在您的代码中使用 __autoload 可能仍然适用于当前版本的 PHP,但预计此功能将在未来被弃用并最终被删除。
那么剩下的选择是:
此版本适用于 PHP 5.3 及更高版本,并允许文件名 SomeSuperClass.php 和 somesuperclass.php。如果您使用 5.3.2 及更高版本,此自动加载器将运行得更快。
<?php
if ( function_exists ( 'stream_resolve_include_path' ) == false ) {
function stream_resolve_include_path ( $filename ) {
$paths = explode ( PATH_SEPARATOR, get_include_path () );
foreach ( $paths as $path ) {
$path = realpath ( $path . PATH_SEPARATOR . $filename );
if ( $path ) {
return $path;
}
}
return false;
}
}
spl_autoload_register ( function ( $className, $fileExtensions = null ) {
$className = str_replace ( '_', '/', $className );
$className = str_replace ( '\\', '/', $className );
$file = stream_resolve_include_path ( $className . '.php' );
if ( $file === false ) {
$file = stream_resolve_include_path ( strtolower ( $className . '.php' ) );
}
if ( $file !== false ) {
include $file;
return true;
}
return false;
});