View Generation and Reserved Names in PHP

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); /* produces array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 
+3
source share
3 answers

Use func_get_arg() instead of using traditional function arguments:

 $buffer = call_user_func(function() { ob_start(); require func_get_arg(0); return ob_get_clean(); }, $path); 
+2
source

You can do this with an extra feature. In the example, I used echo instead of require:

 $path = 'hello'; function valStore($value = null) { static $s = null; if ($value !== null) $s = $value; else return $s; } valStore($path); unset($path); # and gone echo valStore(); 
+2
source

You can use something like this:

 $path = 'path/to/file.php'; function getPath() { global $path; $p = $path; unset($path); return $p; } $buffer = call_user_func(function() { ob_start(); require getPath(); return ob_get_clean(); }); 
+1
source

Source: https://habr.com/ru/post/1379727/


All Articles