I have a question about how to pass the data of a variable from one function (a) to another function (b). For example, in the following case…
function a(){
$a = 8;
}
function b(){
$copy_var = $a
}
I intend that in function b, $copy_var is 8, just as in function a $a is equal to 8. I can’t think of how to do it… Thanx!!
2
Answers
You should take a look at variable scope. Both
$a
and$copy_var
are local variables, which means they exist only within the context of function body, nowhere else, so you cannot point or reference to them.You could use global variable to which both functions have access, but keep in mind that introduce hidden dependency which is generally bad. Example:
Please do not use global variables like this, as you can see now all the sudden the execution order matter due to the hidden dependency.
Imagine following code:
In contrast to:
You see why is it bad ? without looking at both function definitions you have no idea that call to one can affect the other. In complex application this design mistake, which using global variables is in 99% of cases, could cost you hours or even days of frustrating debugging of your application.
Way better is to carry the value through function parameters and return value (maybe even reference but lets keep that away for now), that way you know just by looking at the call code what will happen.
Now the call code is way cleaner, look:
Don’t use
global
, use function parameters and/or return values