Last Updated: February 25, 2016
· zbtirrell

Global keyword can be dangerous


$ape = 'gorrilla';

function test() {
  // a local variable that happens to match a global one
  $ape = 'chimp';

  // assume some stuff happens here...

  // at some point you want to ref the global ape
  global $ape; 

  // assume more stuff happens here....

  // send back ape (did I mean the local one or the global?)
  return $ape;

echo test();  // gorrilla or chimp (protip: it's gorilla)

The global keyword is handy and makes for clean variable names, but it does mess with variable scope so can potentially setup an unpredictable situation.

This is a simple example, but in a situation with a bunch of generically named global variables and long functions, this is something you can truly run into.