I have the following php functions.
function a() {
$var = "variable";
return $var;
}
function b() {
$arr = array('a','r','r','a','y');
return $arr;
}
And some more PHP out of those functions.
$var = a();
$arr = b();
print_r($var);
print_r($arr);
$var
and $arr
are defined in functions, but then are redefined outside of the functions. How do I make it so that the variables and arrays out of the functions are separate from the ones that are in the functions, so that the variables and arrays in the function don't exi开发者_如何学运维st out of the function?
Functions have their own scope. Your function variables do not exist outside of the function unless they are defined using the global
keyword. You may be confusing yourself by using the same variable names both inside and outside of the functions. Try changing the function vars to $fx_arr
and $fx_var
, respectively. You will see that they do not exist outside of the functions.
You need to read more carefully evariable scope in php
$var
declared in a()
is only visible within a()'s
scope. The same goes for $arr
in b()
.
This piece of code $var = a();
should be read this way:
create global (for the scope of the document) variable $var
and assign the value returned by a()
to it.
stepping to a()
we have:
create local (only visible in function scope) variable $var
and assign 'variable' as value, then return the value of $var
.
At the end you ended up with two variables with the same name but with different scope, they do not overlap/overwrite each other because of that.
The opposite is valid too, global variables are not visible in function scopes. You need to use global operator to make them (import them) visible in functions scope.
Hope that helps you. :)
精彩评论