note 95201 deleted from language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Fri, 18 Dec 2009 15:41:33 +0000 |
| Subject: | note 95201 deleted from language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164110@lists.php.net to get a copy of this message | ||
Note Submitter: conor dot rafferty at altsoft dot NI dot com
----
Now I'm laughing (again) at how weird PHP is !
Maybe I'm just contstrained by my C/C++ backround and dont realise how boxed in I am :-)
Anyway, in the below code I was not suprised to see the $GLOBAL array worked in all cases, but
didn't expect the global keyword to work in the lower_level set....
All my anxiety was based on this assumption: when the variable being passed in is NOT a global (i.e.
its declared in a function, that calls this function) it won't work."
Again, I was applying C/C++ nomenclature to PHP, which just ain't safe!
Global in C means declared outside of any other scope (function, class etc. etc.)
But in PHP, it seems from my investigations here that a variable doens't have to be outside of
the other scopes in order to be global.
PS Might be an idea for the PHP documentors to make a note of that, as other ppl coming from the C
familiy of languages could get caught out by this one.
<?php
$top_time = microtime();
$GLOBALS['top_time'] = $top_time;
function top_level($variable) {
echo "In top_level(), \$\$variable is: ".$$variable."<br />";
}
function top_level_use_keyword($variable) {
global $$variable;
echo "In top_level_use_keyword(), \$\$variable is: ".$$variable."<br
/>";
}
function top_level_use_superglobal($variable) {
echo "In top_level_use_superglobal(), \$\$variable is:
".$GLOBALS[$variable]."<br />";
}
top_level('top_time');
top_level_use_keyword('top_time');
top_level_use_superglobal('top_time');
/* RETURNS
In top_level(), $$variable is:
In top_level_use_keyword(), $$variable is: 1261091224
In top_level_use_superglobal(), $$variable is: 1261091224
*/
function lower_level($variable) {
echo "In lower_level(), \$\$variable is: ".$$variable."<br />";
}
function lower_level_use_keyword($variable) {
global $$variable;
echo "In lower_level_use_keyword(), \$\$variable is: ".$$variable."<br
/>";
}
function lower_level_use_superglobal($variable) {
echo "In lower_level_use_superglobal(), \$\$variable is:
".$GLOBALS[$variable]."<br />";
}
function not_global_scope() {
sleep(1);
$lower_time = microtime();
$GLOBALS['lower_time'] = $lower_time;
lower_level('lower_time');
lower_level_use_keyword('lower_time');
lower_level_use_superglobal('lower_time');
/* RETURNS
In lower_level(), $$variable is:
In lower_level_use_keyword(), $$variable is: 0.60494800 1261092050
In lower_level_use_superglobal(), $$variable is: 0.60494800 1261092050 */
}
not_global_scope();
?>