Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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