Global Variables
Published on the 26th of March 2006
Skip to the Table of ContentsSolution - Constants
In many contexts, global variables simply play the role of constants (external link), where the information they hold never changes. In situations like these, use constants instead of globals. Constants are much like global variables, except they are read-only, which eliminates the main problem of global variables - creating complex dependencies. With constants, dependencies are one-way and present less risk of a coding clash.
However, you should still avoid using constants unless it is unquestionably the best solution. Some cases where constants can work well include storing database details, an application's file path, or program settings. Be forewarned, constants - and global variables alike - initially do not fit well with object-oriented programming, and therefore it is recommended to avoid using either if at all possible; however, they fit better with procedural programming.
Solution - Dismissing the Global Variable Concept
The most effective and practical solution to global variables is to just entirely dismiss the concept. It is highly possible to program applications without using global variables; what do you think they do in programming languages that do not support globals? By dismissing globals, you lose the problems of complex dependencies and mutual dependencies.
Programming without globals is extremely easy. Where a class would require information from global variables, you simply pass the needed information into the instances that require it. You can pass the information through the object's constructor when it is created or directly to the method that requires it.
Now we can rewrite our Cat and Dog classes to not use global variables.
PHP
<?php
class Cat {
function meow($times) {
$final = NULL;
for ($x = 0; $x < $times; $x++) {
$final .= 'Meow! ';
}
return $final;
}
}
?>
PHP
<?php
class Dog {
function bark($times) {
$final = NULL;
for ($x = 0; $x < $times; $x++) {
$final .= 'Bark! ';
}
return $final;
}
}
?>
The nice part is that now we can pass any number - whether it be stored in a variable or it is just a plain integer - into either method.
PHP
<?php
$cat = new Cat;
$dog = new Dog;
echo $cat->meow(4).$dog->bark(3);
?>
Meow! Meow! Meow! Meow!
Bark! Bark! Bark!
In the future, we could use either class anywhere without having to have a $times variable in the global scope; each object is self-reliant.
Summary
Global variables can be dangerous to large applications, creating the risk of mutual and complex dependencies. The Singleton design pattern is a common-thought alternative to global variables, which faces the same problems as globals. Two common solutions to globals are to use constants where the variables can be read-only and to dismiss the concept entirely.

