|
Posted by Toby A Inkster on 05/18/07 15:01
Justin Voelker wrote:
> Can anyone explain to me why globals are so bad? I have a $phpEx
> variable in my main config file and i use "global $phpEx" inside of
> certain functions that return links so I don't have to change a
> hundred links if I change my php extension to something else (php4,
> php5). Thanks for the great help everyone! Now if I can just figure
> out how to implement your solutions...
In this example, a constant would be a far better idea:
define('SCRIPT_FILENAME_SUFFIX', '.php');
/* ... */
echo '<a href="login' . SCRIPT_SUFFIX . '">Login</a>';
One argument against the use of a global variable here might be something
like:
// Figure out extension for PHP source code files
function phpSourceExt ()
{
global $phpExt;
if (preg_match('/^\.php([0-9]+)$/i', $phpExt, $matches))
{
return ".php-v{$matches[1]}-source";
}
elseif ($phpExt = '.PHP')
{
return '.PHPS';
}
else
{
return '.phps';
}
}
See what I did there? Single equals sign instead of a double equals sign
in the elseif clause. You can accidentally modify the global variable, and
then the rest of the script will use the modified value. If you use a
constant, PHP raises an error if you try to modify it.
So one bit of code might modify a global variable, and another piece of
code, somewhere way off in another file tries to read the global variable
and has trouble. This is called "action at a distance" and is generally
considered bad. Debugging this kind of thing can be very frustrating, as
you don't know where something went wrong -- so many bits of code using
the same variable.
Which is not to say that global variables aren't occasionally useful. Evil
things can be useful at times. Even Satan himself can be quite handy. But
the forces of evil need great consideration and respect before use. They
have almighty power and need to be handled with care.
Before using global variables, have a good think about if there's a better
way of doing things.
--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python/Apache/Linux
Navigation:
[Reply to this message]
|