-2

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)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pez
  • 172
  • 2
  • 15
  • Maybe you're looking for this answer http://stackoverflow.com/a/7769995/5788489 – Khorshed Alam Oct 17 '16 at 11:36
  • 3
    Possible duplicate of [How to declare a global variable in php?](http://stackoverflow.com/questions/13530465/how-to-declare-a-global-variable-in-php) – akshay Oct 17 '16 at 12:26
  • Guys I know how to declare a global variable that's not what I'm asking, I'll edit – Pez Oct 19 '16 at 08:56

1 Answers1

2

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

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149