I was wondering what exactly happens when I do this:
$my_variable = 'foo';
function whatever(){
$my_variable = 'bar';
global $my_variable;
}
I know that, within the scope of the function $my_variable is now 'foo'.
What's going on internally? When I do $my_variable = 'bar'; inside my function, I've created a local variable. When I do global $my_variable; on the next line what exactly happens? The local one is automatically deleted?
Up until the global is processed, the function will be using the local bar copy of the varaible. Once it's declared global, the local version is hidden (or maybe destroyed, not sure...) and only the global version is available. e.g:
$z = 'foo';
function whatever() {
echo $z; // warning: undefined variable
$z = 'bar';
echo $z; // bar
global $z;
echo $z; // foo
}
whatever();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With