View generation and reserved names in PHP

隐身守侯 提交于 2019-12-23 17:33:35

问题


This is a bit of a peculiar one; I don't think this is in fact possible, however the SO community has surprised me time and time again; so here goes.

Given 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 included, path/to/file.php will have $path in it's scope. Is there any way to prevent this variable from being available in the context of the included file?

For instance, given unset() returned the value of the variable it was unsetting, I could do:

require unset($path);

But of course that doesn't work.


For those curious, I'm trying to prevent $path from inheriting a value from the include-er.

"Security-by-obfuscation" is a consideration I made; passing something like $thisIsThePathToTheFileAndNobodyBetterUseThisName, but that seems a bit silly and still isn't foolproof.

For other "reserved" variables that should be inherited, I've 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 misleading, through my use of use() to pass variables into the anonymous function scope; passing arguments was an option I neglected to 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)
}

回答1:


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:


You can do this with the help of an additional function. 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();



回答3:


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();
});


来源:https://stackoverflow.com/questions/6839659/view-generation-and-reserved-names-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!