开发者

View generation and reserved names in PHP

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 misleadin开发者_JS百科g, 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)
}


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜