Re: Good way to make variables global (?)

From: Date: Tue, 10 Oct 2000 00:32:26 +0000
Subject: Re: Good way to make variables global (?)
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-19269@lists.php.net to get a copy of this message
Erica Douglass writes: > I recently stumbled upon a way to make all variables global. I did this > because I got sick of writing out global variable after global variable in > my functions. > > It seems to work just great in my script, but I wanted to read others' > input on this. The advantages are obvious: no huge GLOBAL declarations. > However, I wanted to know if there are any hidden pitfalls that I haven't > noticed (besides the fact that a global variable could be easily overwritten.) > > Here's the code: > > function example_function () { > reset ($GLOBALS); > while ( list($key, $val) = each($GLOBALS) ) { > extract ($GLOBALS); > } > > My impression: This is a very cool snippet of code... as long as you > understand the implications. > > Erica Here's the first thing I notice: the above code extracts _all_ elements of $GLOBALS, for _each_ element of $GLOBALS. In other words, extract() already extracts() all of the elements of the array it is given; you don't need to do it once for each element. So if your $GLOBALS array has, say, 20 elements, the above code is doing 20 times the work it needs to do. Try this: function example_function() { extract($GLOBALS); . . . } Or for those still running PHP 3: function example_function() { reset($GLOBALS); while (list($key) = each($GLOBALS)) { if ($key != 'GLOBALS') { // Just to suppress a warning global $$key; // This is the important bit } } . . . } ObDisclaimer: :) Personally, however, I wouldn't use either form (or anything like this) in production code. Overusing globals makes it way, way too easy to lose track of what information is coming from where, what is getting modified where, and makes it tougher to reuse and maintain the code. -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#19269) next »