在PHP中查看生成和保留名称
这有点特别;我认为这实际上是不可能的,但 SO 社区一次又一次让我感到惊讶;所以这里。
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.
在PHP中给出;我有以下代码段:
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();
});
如果包含, path / to / file.php
在其范围内将有 $ path
。 有没有办法阻止此变量在包含文件的上下文中可用?
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?
例如,给定 unset()
返回它未设置的变量的值,我可以这样做:
For instance, given unset()
returned the value of the variable it was unsetting, I could do:
require unset($path);
但当然不起作用。
对于那些好奇的人,我试图阻止 $ path
继承include- 中的值呃。
For those curious, I'm trying to prevent $path
from inheriting a value from the include-er.
通过混淆安全是我所做的考虑;传递类似 $ thisIsThePathToTheFileAndNobodyBetterUseThisName
之类的东西,但这看起来有点傻,但仍然不是万无一失。
"Security-by-obfuscation" is a consideration I made; passing something like $thisIsThePathToTheFileAndNobodyBetterUseThisName
, but that seems a bit silly and still isn't foolproof.
其他保留应继承的变量,我已经使用 extract()
和 unset()
:
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();
// ...
编辑:
我最终选择的是:
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);
也许我的问题有点儿误导,通过我使用 use()
将变量传递到匿名函数范围;传递参数是我忽略的选项。
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.
关于@hakre和 use()
+ func_get_args()
:
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)
}
使用 func_get_arg()
而不是使用传统的函数参数:
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);