Last active
August 1, 2019 12:48
-
-
Save waqashassan98/6139accb8ba917e6579829e3eb1984a4 to your computer and use it in GitHub Desktop.
Autoloading Classes PHP
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 | |
//src: https://www.php.net/manual/en/function.spl-autoload-register.php | |
// Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method. | |
// It auto-loads any file it finds starting with class.<classname>.php (LOWERCASE), eg: class.from.php, class.db.php | |
spl_autoload_register(function($class_name) { | |
// Define an array of directories in the order of their priority to iterate through. | |
$dirs = array( | |
'project/', // Project specific classes (+Core Overrides) | |
'classes/', // Core classes example | |
'tests/', // Unit test classes, if using PHP-Unit | |
); | |
// Looping through each directory to load all the class files. It will only require a file once. | |
// If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once! | |
foreach( $dirs as $dir ) { | |
if (file_exists($dir.'class.'.strtolower($class_name).'.php')) { | |
require_once($dir.'class.'.strtolower($class_name).'.php'); | |
return; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment