简体   繁体   中英

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["NameOfTheVariableDefinedInInclude"]; // 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM