Declaring a global array

Nistor Alexandru picture Nistor Alexandru · Oct 13, 2012 · Viewed 75.6k times · Source

Hi. I recently learned PHP and am trying to declare a global array so I can access inside a function. But I seem to be missing something because I get the error 'Undefined variable:'

Here is my code:

global $second_array;
$second_array = array();

function operatii($v) {
  $var1 = $second_array[count($second_array)-1];
  $var2 = $second_array[count($second_array)-2];
  $rez = null;

  echo $var1 . $var2 . "este?";
}

for ($i = 0; $i < count($a); $i++){
  if ($a[$i] === "+" || $a[$i] === "-" || $a[$i] === "*" || $a[$i] === "/" ) {
    operatii($a[$i]);
  } else {
    array_push($second_array, $a[$i]);
  }
}

I seem to be able to use the $second_array in the for loop, but can't use it in the operatii function.
How can I solve this problem?

Answer

Spudley picture Spudley · Oct 13, 2012

There are two ways to reference a global variable in PHP:

  1. Use the global keyword at the start of every function that uses the variable.
  2. Use the $GLOBALS array.

Of these, I recommend sticking with the second, since it makes it absolutely clear at all times that the variable is a global.

One of the problems with globals is keeping track of where they're being used; using the $GLOBALS array mitigates this issue to some extent.

However, there are still issues with using globals; it's generally considered poor practice to use too many globals in your code. Having worked with a number of legacy systems that used globals extensively, I can vouch for the fact that they can cause a lot of headaches for future developers.

Using globals also makes it harder to write formal test suites for your code (ie unit tests).

My recommendation would therefore be to avoid using globals at all where possible. They are necessary in some cases, but the more you can avoid them, and instead pass variables into your functions and classes rather than making them global, the better things will be.

So to summarise:

If you must use globals, reference them with $GLOBALS['varname'], but it's usually better not to use them at all.

Hope that helps.