I have a small problem in a script I can't solve on my own. Having studied the PHP documentation regarding variable scope, I am not sure if this is even possible.
Take the following example:
function my_funct_a() {
// Do stuff
return $a;
}
function my_funct_b() {
// Do other stuff
return $a + $b;
}
You see, the problem is that in my_funct_b
, $a
is not available because it was declared (and is returned) in my_funct_a
.
Normally I would pass this variable as an argument, but this is not possible at this point due to some kind of framework limitation.
So I tried to do it like this:
function my_funct_a() {
// Do stuff
global $a;
return $a;
}
function my_funct_b() {
// Do other stuff
global $a;
return $a + $b;
}
This also didn't work, I think because global
works 'the other way around'. Instead of declaring a variable as global inside a function to be available outside the function, it has to be declared as global outside the function to be available inside the function.
The Problem is that the value of $a
is created in my_funct_a
, so I can't global it before the value is known.
Because of that, I tried to do it like this:
// global variable, but no value assigned yet
global $a
function my_funct_a() {
// Do stuff
global $a;
$a = 1;
return $a;
}
function my_funct_b() {
// Do other stuff
global $a;
return $a + $b;
}
This also didn't work. Why? Is it even possible without passing the variable as an argument?
my_funct_b()
, how do you get$b
? Same question formy_funct_a()
btw.$a
is a dynamic value created inside that function,$b
is a string using that dynamic value. I am afraid I have to to it using the two functionsglobal
works is wrong. You declare it inside the function, and it allows that function to access the global variable with that name. Your second try should have worked.