3

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?

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

I believe when the global is called, the local version destroyed right there. I infer this from the action of unset() within a function and this statement in the unset docs : If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
2

Yes, the local one is automatically deleted or probably better worded, it is replaced with the global variable.

Comments

0

Think of it like this:

$GLOBALS['my_variable'] = 'foo';
function whatever(){
    $my_variable = 'bar';
    $my_variable = $GLOBALS['my_variable'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.