$ GOBALS在闭包中未定义

时间:2015-02-22 03:45:12

标签: php lambda scope closures globals

我有这种轻微的困境,我似乎无法在以下代码中访问$GLOBALS

$closure = function()
{
$key = 'some_key';  //define a key
$GLOBALS[$key] = 'a value';  //assign a value to the key position on $GLOBALS -- THIS WORKS
$variable = "GLOBALS";  //grab GLOBALS as a string

$ref = $$variable;  //grab a reference to the variable defined in $variable -- THIS FAILS
echo $ref[$key];  //output the value
};
$closure();

//output:  Undefined variable: GLOBALS in test.php

虽然这在这里工作正常:

$key = 'some_key';
$GLOBALS[$key] = 'a value';
$variable = "GLOBALS";

$ref = $$variable;
echo $ref[$key];  //outputs "a value"

我的问题的一个奇怪的解决方案是以下(但我想知道为什么我的代码破坏):

$closure = function()
{
$globals = $GLOBALS;  //this works
$GLOBALS = $GLOBALS;  //this... doesn't work however
$key = 'some_key';
$GLOBALS[$key] = 'a value';
$variable = "globals";

$ref = $$variable;
echo $ref[$key];
};
$closure();

我遇到这个麻烦的原因是避免以下情况:

$key = 'key'; // or variable, where the output is GLOBALS (not variable)
$GLOBALS[$key] = 'something different, ergo key no longer points towards GLOBALS[KEY]';
$variable = "GLOBALS";

$ref = $$variable; 
echo $ref[$key];

// outputs Notice: Undefined index: something different, ergo key no longer points towards GLOBALS[KEY] in test.php

0 个答案:

没有答案