Usage has gotcha, although this is by far the fastest method, it also expects all of your file names to be lowercase.
spl_autoload_extensions(".php"); spl_autoload_register();
For example:
The file containing the SomeSuperClass class should be named somesuperclass.php, this will be obtained using a case-sensitive file system such as Linux, if your file is called SomeSuperClass.php, but not a problem on Windows.
Using __autoload in your code may still work with current versions of PHP, but expect this feature to become obsolete and finally removed in the future.
So what options are left:
This version will work with PHP 5.3 and higher and allows the file names SomeSuperClass.php and somesuperclass.php. If you use 5.3.2 and higher, this autoloader will run 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; });
Michael Bush Apr 08 '15 at 1:28 2015-04-08 01:28
source share