Plain and simple like the title says - Is there any way to programmatically declare globals inside a function in PHP? For example, from an array of strings (which are the global variables names)
Yes, if you add variables to the $GLOBALS
array they are then globally available like any other global.
function add_globals($arr)
{
foreach ( $arr as $idx => $name ) {
$GLOBALS[$name] = $idx;
}
}
$names = array('aa','bb');
add_globals($names);
echo $aa.PHP_EOL;
echo $bb.PHP_EOL;
RESULT
0
1
I am just using the index of the $names array as a value for each new global, you could use anything