Hello, please sign in or register
You are here: Home

Globals in functions can be discombobulating

Defining globals create tied functions (i.e. not a good modular piece of code). If the globally defined $r[market][currency]; for whatever reason became an array of variables (or was changed completely to $s[country][cur]; instead) the function would return mysterious results, even if the coder were sure all input arguments were sanitized.

Ok, My hands up, I’ve also written global $d into a function not too long ago, and it does save time, especially where we known of these common variables. But let’s consider some examples of unexpected behavior, and why it’s fraught with woe.

Case 1 -The Trojan function

Consider the following

function benevolent()
                global $r;
                // destroy all Mu Ha Ha
                $r = “”;
$r = array(“All my worldly possessions”, “My Family”);

if ( empty($r) )
                Echo “They’re all gone”;

… which is an extreme example, but whilst mistakes do happen I would find it difficult to associate the loss of my variable $r, with my “benevolent” function.

Case 2 - The unexpected variable.

In this case it creates a variable in the global scope.

function unexpectedvariable()
      global $s;
     $s = “Didn’t expect me”;


If ( !isset ($s) )
                $s = “This is what you expected”;

echo $s;


The CONSTANT alternative.

Constants e.g. define('MYCONST', 'value'); are similar because they also have a “magical” effect on the functions result. and they dont need to be declared as arguments. However they are limited to being scalar and are immutable. So i dont mind them too much. Although will always prefer regular arguments.

... But thats not great either.

One way in, One way out

The best functions are easy to document and easy to share. And to a degree self explanatory, however avoid ever arguing "Good code explains itself" its optimistic at best and i am not you. The One way in and one way out design. Means: dont set or get variables by reflection or globals. Stick to argument parameters and return method.


This hilfiger outlet time swarovski jewelry something really timberland outlet strange, ...
Created 30/06/16
ninest123 One canada goose pas cher gucci outlet thing
Created 21/07/16

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Email never shown*
Home Page


Andrew Dodson
Since:Feb 2007

Comment | flag


Bookmark and Share