Variable scope outside of functions
Posted: Thu Mar 25, 2004 9:13 pm
Hi, I'm trying to make a script that includes one function that is called multiple times. I want it to increment a variable each time that function is called for the duration of the script, and then echo it after the series of functions are called.
Each time I've tried this I've failed, since apparently the variable may only be recalled within the function. Outside of the function, whether it's declared global or not, it will not remember what that variable was.
It does increment the variable correctly, since I've tested it, it's just that after the series of functions are called, it will not echo the incremented variable as it should.
Here's a simplified version of what I'm trying to do:
What that does is print:
1
2
3
4
1
I want it to print:
1
2
3
4
4
One peculiar thing that makes me hit my head more is that I also did this:
That would print $b with all the data from each function... why wouldn't the same be for the last one?
Again, I've tried to get rid of the static, the global, and variations on that... all unsuccessful. I'd appreciate any help.
Each time I've tried this I've failed, since apparently the variable may only be recalled within the function. Outside of the function, whether it's declared global or not, it will not remember what that variable was.
It does increment the variable correctly, since I've tested it, it's just that after the series of functions are called, it will not echo the incremented variable as it should.
Here's a simplified version of what I'm trying to do:
Code: Select all
$a = 1;
function a()
{
global $a;
static $a;
echo $a . "<br>";
$a++;
}
a();
a();
a();
a();
echo $a;1
2
3
4
1
I want it to print:
1
2
3
4
4
One peculiar thing that makes me hit my head more is that I also did this:
Code: Select all
function a();
{
$b .= something different each time the function is called;
}
a();
a();
a();
echo $b;Again, I've tried to get rid of the static, the global, and variations on that... all unsuccessful. I'd appreciate any help.