Last active
June 21, 2018 16:18
-
-
Save sergeliatko/ac2ea7eb3fe676fe5b2d5b6eacc4bc47 to your computer and use it in GitHub Desktop.
PSR4 Autoloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PSR-4 Autoloader. | |
*/ | |
spl_autoload_register( function ( $class ) { | |
// validate namespace | |
if ( | |
strncmp( | |
$namespace = 'Vendor\\Package',#namespace | |
$class, | |
$namespace_length = strlen( $namespace ) | |
) !== 0 | |
) { | |
return; | |
}; | |
// try to load the file | |
if ( file_exists( | |
$file = join( | |
DIRECTORY_SEPARATOR, | |
array( | |
__DIR__, | |
'src',#sources directory name | |
str_replace( '\\', DIRECTORY_SEPARATOR, trim( substr( $class, $namespace_length ), '\\' ) ) | |
) | |
) . '.php' | |
) ) { | |
include $file; | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PSR-4 autoloader for your packages that uses DIRECTORY_SEPARATOR constant. Just make sure to update the values marked with comments: