This is a solution for a problem that I had and could not find an answer for anywhere. It involves Global Variable Scope and multiple functions.
Basically, I wanted one function to declare variables and then have a second nested function use those variables. This works fine when a script declares the variables and then calls a function that uses those variables after declaring global $var1, $var2;
.
However, I had problems with the nested function seeing variables that the parent function declared, using the same code logic as for a script calling a function.
The solution was to write:
function function_1(){
global $var1, $var2;
$var1=0;
$var2=0;
function function_2(){
global $var1, $var2;
}
function_2();//call to nested function.
}
All variables interact properly in this case.
If you state 'global' after you declare the variables in function_1, you simply wipe out the value of the variables (you declare new variables with no values?).
Hope this helps someone :)
Greg
Don't use global variables. Use use ($var1,$var2)
so you do not need to globalize your variables
To illustrate what genesis was saying, do the following:
function func1($a, $b) // <-- function DEFINITION for func1
{
// do stuff wit $a and $b
func2($a, $b); // <-- function INVOCATION of func2 within func1
}
func2($y, $z) // <-- function DEFINITION for func2
{
// do stuff with $y and $z
}
// --------------------------------
$param1 = "some value";
$param2 = "some other value";
func1($param1, $param2); // <-- explicit INVOCATION of func1... func2 is also invoked within
Never use the 'global' keyword to pass parameters into a function. Functions have argument lists for a reason.
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