<?php
class ImportItemError extends Exception {}
class ImportFileError extends Exception {}
function import($file) {
static $imported = array();
$file = realpath($file);
if (isset($imported[$file])) {
return $imported[$file];
}
try {
$imported[$file] = new Import($file);
return $imported[$file];
}
catch (ImportFileError $e) {
return false;
}
}
class Import {
private
$_variables = array(),
$_constants = array(),
$_functions = array(),
$_classes = array();
public function __construct($file) {
if (!is_file($file)) {
throw new ImportFileError('Unable to find "'.$file.'" for import.');
}
// Get the variables and execute the script
$this->pre_vars = get_defined_vars();
include $file;
$this->post_vars = get_defined_vars();
$this->_variables = array_diff($this->post_vars, $this->pre_vars);
// Get the functions and the classes
$contents = file_get_contents($file);
preg_match_all('/function\s+([a-zA-Z0-9_]+)/', $contents, $functions);
preg_match_all('/class\s+([a-zA-Z0-9_]+)/', $contents, $classes);
$this->_functions = $functions[1];
$this->_classes = $classes[1];
// Clean out methods confused as functions
foreach ($this->_functions as $key => $function) {
if (!function_exists($function)) {
unset($this->_functions[$key]);
}
}
sort($this->_functions);
}
public function allVariables() {
return $this->_variables;
}
public function allConstants() {
return $this->_constants;
}
public function allFunctions() {
return $this->_functions;
}
public function allClasses() {
return $this->_classes;
}
public function __get($item) {
if ($key = array_search($item, $this->_classes)) {
return $this->_classes[$key];
}
elseif (isset($this->_variables[$item])) {
$this->_variables[$item];
}
else {
throw new ImportItemError('Imported variable or class "'.$item.'" not found.');
}
}
public function __call($item, $args = array()) {
if ($key = array_search($item, $this->_classes)) {
return $this->_classes[$key];
}
elseif (in_array($item, $this->_functions)) {
return call_user_func_array($item, $args);
}
else {
throw new ImportItemError('Imported function or class "'.$item.'" not found.');
}
}
}
?>