Using has a gotcha, while it is by far the fastest method, it also expects all of your filenames to be lowercase.
spl_autoload_extensions(".php");
spl_autoload_register();
For example:
A file containing the class SomeSuperClass would need to be named somesuperclass.php, this is a gotcha when using a case sensitive filesystem like Linux, if your file is named SomeSuperClass.php but not a problem under Windows.
Using __autoload in your code may still work with current versions of PHP but expect this feature to become deprecated and finally removed in the future.
So what options are left:
This version will work with PHP 5.3 and above and allows for filenames SomeSuperClass.php and somesuperclass.php. If your using 5.3.2 and above, this autoloader will work even faster.
<?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;
});
AS
. That's not why this solution works. You could just as easily do:use Person\Barnes\David\Class1;
(which is equivalent touse Person\Barnes\David\Class1 as Class1;
). – Utley