0

I was hoping the below would print

live
got here

Instead it prints

got here

The code:

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {

  echo $config['env'];
  echo 'got here';

}

How do I set this global variable and have everything inside a function access it?

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • 3
    Possible duplicate of [How to declare a global variable in php?](https://stackoverflow.com/questions/13530465/how-to-declare-a-global-variable-in-php) – Nico Haase May 15 '18 at 11:16
  • Globals are generally not a good sign. A constant might make more sense for this, since I'm assuming the environment won't change at run-time. There are details in the duplicate question. – iainn May 15 '18 at 11:20

3 Answers3

3

Use global to use global variables inside functions:

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
  global $config;
  echo $config['env'];
  echo 'got here';
}

Or if you have anonymous function, you can use use:

$sayEnvironment2 = function () use ($config) {
    echo $config['env'];
    echo 'got here';
};

$sayEnvironment2(); // must be called AFTER php parser has seen actual function.

Sample

Justinas
  • 41,402
  • 5
  • 66
  • 96
1

here you go,

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
global $config;
  echo  $config['env'];
  echo 'got here';

}
GYaN
  • 2,327
  • 4
  • 19
  • 39
Soul Coder
  • 774
  • 3
  • 16
  • 40
0

To answer your question, you can use PHP $GLOBALS for this:

<?php

$GLOBALS['config']['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
  echo $GLOBALS['config']['env'];
  echo 'got here';

}

It's not really considered a good practise to do the above though, but without knowing what you're aiming for it's hard to advise another method. Usually some form of dependency injection would be better.

Docs for it: http://php.net/manual/en/reserved.variables.globals.php

Mikey
  • 2,606
  • 1
  • 12
  • 20