$ GOBALS не определено в закрытии

У меня есть небольшая дилемма, кажется, я не могу получить доступ $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

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector