It is a little peculiar; I don't think this is really possible, but the SO community has surprised me again and again; so here it goes.
Provided in PHP; I have the following snippet:
$path = 'path/to/file.php'; $buffer = call_user_func(function() use($path){ ob_start(); require $path; return ob_get_clean(); });
When enabled, path/to/file.php will have $path in its scope. Is there a way to prevent this variable from being accessed in the context of the included file?
For example, this unset() returned the value of a variable that it did not set, I could do:
require unset($path);
But of course this does not work.
For the curious, I'm trying to prevent $path from inheriting the value from include-er.
"Protection against obfuscation" is a consideration that I have made; passing something like $thisIsThePathToTheFileAndNobodyBetterUseThisName , but that seems a little silly and still not reliable.
For other "reserved" variables that should be inherited, I already went with extract() and unset() :
$buffer = call_user_func(function() use($path, $collection){ extract($collection); unset($collection); ob_start();
Edit:
What I finally went with:
$buffer = call_user_func(function() use(&$data, $registry){ extract($registry, EXTR_SKIP); unset($registry); ob_start(); // only $data and anything in $registry (but not $registry) are available require func_get_arg(0); return ob_get_clean(); }, $viewPath);
Perhaps my question was a bit erroneous, thanks to using use() to pass variables into the scope of an anonymous function; passing arguments was an option that I did not mention.
Regarding @hakre and use() + func_get_args() :
$var = 'foo'; $func = function() use($var){ var_dump(func_get_args()); }; $func(1, 2, 3);