Re: Local variable protection
| From: | Tedd Sperling | Date: | Thu, 13 Oct 2011 15:25:05 +0000 |
| Subject: | Re: Local variable protection | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-315272@lists.php.net to get a copy of this message | ||
>> 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@sperling.com
http://sperling.com