Why aren't variables defined inside an include defined in the $GLOBALS array?
I'm trying to access a dynamically named variable that is defined inside an include file after the include is included, for example:
require "/path/to/my/include.php"; echo $_VariableDefinedInInclude; // outputs the variable echo $GLOBALS["NameOfTheVariableDefinedInI开发者_运维问答nclude"]; // nothing outputs?
Any idea why the variable is not in the $GLOBALS array? Is there a function like constant() but for standard variables that I could use to dynamically access the variable by its name?
Thanks
The $GLOBALS array only applies to variables set with the global keyword. If you are including another file, it is essentially the same as the code being all in the same file. In other words, you still have access to that variable in the same scope. There is no need to use $GLOBALS or anything. Additionally, if that variable is constant, you can use const (PHP 5.3) or define('KEY', $val) to define it as a constant instead.
Given that the variable is dynamically-named, perhaps:
echo $GLOBALS[$GLOBALS["NameOfTheVariableDefinedInInclude"]];
will do the trick.
精彩评论