Variable scope outside of functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
prov
Forum Newbie
Posts: 10
Joined: Thu Mar 25, 2004 9:13 pm
Location: Providence, RI
Contact:

Variable scope outside of functions

Post by prov »

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:

Code: Select all

$a = 1;
function a()
{
global $a;

static $a;

echo $a . "<br>";

$a++;
&#125;

a();
a();
a();
a();

echo $a;
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:

Code: Select all

function a();
&#123;
$b .= something different each time the function is called;
&#125;

a();
a();
a();

echo $b;
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. :)
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

With the first example you don't need a fn: just increment $a wherever you need to.

The second surely doesn't echo anything - $b is not in the global scope?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

First example would work as expected if you remove the static definition. You just redefined the $a var in the scope of the function, no wonder that global var hadn't got incremented.
Post Reply