note 70998 deleted from language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:34:26 +0000 |
| Subject: | note 70998 deleted from language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155554@lists.php.net to get a copy of this message | ||
Note Submitter: Michael
----
davo971 (http://us2.php.net/manual/en/language.variables.scope.php#69765), it seems you're
encountering the same mental block that jason
(http://us2.php.net/manual/en/language.variables.scope.php#65337) was having. I know how that goes,
because I used to have this problem as well. Don't think of permission to access a variable as
being transferred from function to function. There is exactly 1 global scope in any script, and
that's the scope outside of all functions and classes. If you specify a variable as global, it
does not mean you are accessing a variable in the calling function's namespace, it means you
are accessing the variable in the global namespace. In your example, you seemed to think that
declaring $new_var global in function2() would give it access to variables declared in
function1()'s namespace. In fact, acess to variables does not propagate up the function
stack--declaring you wish to work on a global variable ALWAYS gives you access to the SINGLE
variable declared in the global namespace with that name. It's more easily understood when you
work with the $GLOBALS array... there's only 1 such array, and consequently there's
exactly 1 of each global variable. So if we modify your example to work correctly, here's what
it'll look like:
<?php
$var = 'foo';
$new_var = 'asdf';
function function1()
{
global $new_var; //Now working with global $new_var, declared above
$new_var = 'bar'; //Changing $new_var from 'asdf' to 'bar'
function2();
}
function function2()
{
global $var, $new_var; //Accessing global variables $var and $new_var, declared outside any
functions
echo($var . $new_var);
}
function1();
?>
Outputs foobar