note 70998 added to language.variables.scope
| From: | Michael at osu1 dot php dot net | Date: | Tue, 07 Nov 2006 18:35:08 +0000 |
| Subject: | note 70998 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-119485@lists.php.net to get a copy of this message | ||
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
----
Server IP: 64.71.164.2
Probable Submitter: 128.174.73.20
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/70998
Del: integrated -- https://master.php.net/note/delete/70998/integrated
Del: useless -- https://master.php.net/note/delete/70998/useless
Del: bad code -- https://master.php.net/note/delete/70998/bad+code
Del: spam -- https://master.php.net/note/delete/70998/spam
Del: non-english -- https://master.php.net/note/delete/70998/non-english
Del: in docs -- https://master.php.net/note/delete/70998/in+docs
Del: other reasons-- https://master.php.net/note/delete/70998
Reject -- https://master.php.net/note/reject/70998
Search -- https://master.php.net/manage/user-notes.php