Skip to content

Instantly share code, notes, and snippets.

@Rene-Sackers
Last active August 29, 2015 14:23
Show Gist options
  • Save Rene-Sackers/6795b983825fc6a720ef to your computer and use it in GitHub Desktop.
Save Rene-Sackers/6795b983825fc6a720ef to your computer and use it in GitHub Desktop.
Isolated include
<?php
var_dump(get_defined_vars());
<?php
/**
* Includes a file with an empty variable scope.
* @param string $filePath The path to the file to include.
* @param array|null $variables Key/value array with the variables that should be in the include file its scope.
* @param bool $useRequire Wehter to use require() instead of include()
*/
function isolatedInclude($filePath, $variables = null, $useRequire = true) {
unset($filePath, $variables, $useRequire);
if (count(func_get_args()) >= 2 && func_get_arg(1) !== null) {
extract(func_get_arg(1));
}
if (count(func_get_args()) < 3 || func_get_arg(2) === true) {
require func_get_arg(0);
} else {
include func_get_arg(0);
}
}
$parentScopeVariable1 = 'Parent variable 1';
$parentScopeVariable2 = 'Parent variable 2';
$includeScopeVariable1 = 'Include scope variable 1';
$includeScopeVariable2 = 'Include scope variable 2';
isolatedInclude('include_file.php', ['includeScopeVariable1' => $includeScopeVariable1, 'includeScopeVariable2' => $includeScopeVariable2]);
array (size=2)
'includeScopeVariable1' => string 'Include scope variable 1' (length=24)
'includeScopeVariable2' => string 'Include scope variable 2' (length=24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment