Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Last active December 28, 2018 09:49
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/59f0770ee190e0d71feae0e76cbed786 to your computer and use it in GitHub Desktop.
Save Abhinav1217/59f0770ee190e0d71feae0e76cbed786 to your computer and use it in GitHub Desktop.
A php package simulation with a java style syntax. <Simple way>
<?php
$basePath = "./";
/**
* A simple implementation of Java's import statement.
*
* 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 autoloading is the way to go.
*
* Taken from https://www.codediesel.com/php/simulating-packages-in-php/ All credit goes to them.
*
* @param <string> $classPath Path of php file to be imported.
*/
function import($classPath)
{
global $basePath;
/* If the path ends with a '.*' then include
all the files in the last given directory.
*/
if(preg_match('/(\.\*)$/', $classPath))
{
$importFilePath = substr($classPath, 0, strlen($classPath) - 2);
$importFilePath = str_replace(".", "/", $importFilePath);
$d= dir($basePath . $importFilePath);
while(false !== ($file = $d->read()))
{
/* Reject parent, current directories and sub directories */
if(($file == '.') ||
($file == '..') ||
(is_dir($d->path . "/" . $file)))
{
continue;
}
require_once($basePath . $importFilePath . "/" . $file);
}
} else {
/* If a single file is specified */
$importFile = str_replace(".", "/", $classPath) . ".php";
require_once($basePath . $importFile);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment