Re: Local variable protection

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



>> On Oct 12, 2011, at 4:24 PM, Ken Robinson wrote:
>> Yes, but scope does not necessarily protect a value.  Within a function
>> globals are out of scope, but their values can still be accessed through
>> $GLOBALS.

Tangental to the main point (and probably obvious to many) but I used to believe (until recently) that variables within a $GLOBAL had to be defined before being used, such as:

$GLOBAL['myVar'] = 'test';
echo($GLOBAL['myVar']);

But that is not true.

You can do this:

$myVar = 'test';
echo($GLOBAL['myVar']);

And reach the same result.

What is true (which I found surprising) was that any variable defined within the main script are automatically included in the $GLOBAL array.

So, if in your main script you have the statement:

$myVar = 'test';

Then the $GLOBAL['myVar'] has also been created and will hold the value of 'test' without any additional coding.

While many of you will say "But of course, that's the way it works." I actually said "What?!?" You see, I seldom use globals in my scripts and this runs counter to my 'keep the globals to an absolute minimum' practice. So while I was thinking my scripts didn't have globals, it was a surprise to me to find out that in the background they were present anyway.

So, if you want a main script variable (i.e., $myVar) to be accessed by a function, you can do it by stating:

myFunction
   {
   global $myVar;
   // and then using $myVar
   }

or

myFunction
   {
   $myVar = $GLOBAL['myVar'] 
   // and then using $myVar
   }

or via the standard ways by sending the value (or reference) to the function.

I hope my ignorance helps someone.

Cheers,

tedd

_____________________
tedd@xxxxxxxxxxxx
http://sperling.com
-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux