PHP and function scope

若如初见. 提交于 2020-01-11 06:34:06

问题


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?


回答1:


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();



回答2:


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




回答3:


Think of it like this:

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


来源:https://stackoverflow.com/questions/11821548/php-and-function-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!