You can't escape Global Variables

July 29th, 2009, 3:38 pm

It is commonly taught that global variables are “relics” of poor practice by beginning programmers, and therefore should be avoided. However, like the infamous <table> tag, globals still perform a function that is required in programming. The fact is that we need access to our objects from all manner of locations.

Take PHP for example, no self-respecting programmer would admit to using the global keyword to fetch object instances. The main reason is that a global instance could be accidentally overwritten or changed the same way as normal variable. You could say that by using “global” you are allowing read & write access to the object it’s self which might lead to problems down the road.

To stop this bad practice, programmers begin a Holy War against globals when all that was really needed was to remove write access to the object. Because of this new ways to keep objects global began emerging - however, at their basic level they are nothing more than alternative methods of storing and fetching globals.


//EVIL Global Variables
global $class;
$class->method();

//Global Static classes
CLASS::method();

//Global throughout object instance (MVC Frameworks)
$this->class->method();

//Global from static singlton instances
$class = CLASS::instance();
$class->method();

It is time to start correctly explaining global objects in a balanced way. Not in miss-placed confusion about the usefulness of accessing values where they are needed. While I don’t recommend we start using “global” again, we do need to represent the concepts correctly.

Comments

No comments yet! Be the first to add one!

Add Your Insight

Please keep your comments clean and helpful. Those cool images you see next to people are their gravatars. You can use obvious HTML. Wrap Code with <code> and </code> (PHP needs the opening an closing tags too!). No substitutions, extensions, or refunds. Void where IE is used. Cash not accepted. I make the rules. Se habla espanol, marko numeral uno.