Last Updated: February 25, 2016
·
683
· zbtirrell

Global keyword can be dangerous

<?php

$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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
#global
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside