Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Created December 28, 2018 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abhinav1217/64e6d6e22d5a75ff6f4b129016fb74a4 to your computer and use it in GitHub Desktop.
Save Abhinav1217/64e6d6e22d5a75ff6f4b129016fb74a4 to your computer and use it in GitHub Desktop.
<?php
/**
* A more complete implementation of Java's import statement. For `PHP >=5.0, <=7`
*
* While we do not need it in modern projects, I found this to be really
* helpful for teaching purposes.
*
* This is for teaching purposes only. In real life, composer and namespacing is the way to go.
*
* Taken from http://jacwright.com/40/php-package-management-and-autoloading/ All credit goes to them.
*
*/
$imports = array();
function __autoload($className) {
loadClass($className);
}
function loadClass($className) {
global $imports;
if (isset($imports[$className])) {
include_once($imports[$className]);
}
}
function import($import) {
global $imports;
// seperate import into a package and a class
$lastDot = strrpos($import, '.');
$class = $lastDot ? substr($import, $lastDot + 1) : $import;
$package = substr($import, 0, $lastDot);
// if this import has already happened, return true
if (isset($imports[$class]) || isset($imports[$package.'.*'])) return true;
// create a folder path out of the package name
$folder = '' . ($package ? str_replace('.', '/', $package) : '');
$file = "$folder/$class.php";
// make sure the folder exists
if (!file_exists($folder)) {
$back = debug_backtrace();
return trigger_error("There is no such package <strong>'$package'</strong> -- Checked folder <strong>'$folder'</strong><br />
Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
} elseif ($class != '*' && !file_exists($file)) {
$back = debug_backtrace();
return trigger_error("There is no such Class <strong>'$import'</strong> -- Checked for file <strong>'$file'</strong><br />
Imported from <strong>'{$back[0]['file']}'</strong> on line <strong>'{$back[0]['line']}'</strong><br />", E_USER_WARNING);
}
if ($class != '*') {
// add the class and it's file location to the imports array
$imports[$class] = $file;
} else {
// add all the classes from this package and their file location to the imports array
// first log the fact that this whole package was alread imported
$imports["$package.*"] = 1;
$dir = opendir($folder);
while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.php')) {
$class = str_replace('.php', '', $file);
// put it in the import array!
$imports[$class] = "$folder/$file";
}
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment