black_belt
black_belt

Reputation: 6799

Static variable in PHP

If I run the following PHP code, I get 123. I don't understand the logic behind it. What I think is when I call the function each time it suppose to output 1. So the output should be like 111.

function keep_track() {
  STATIC $count = 0;
  $count++;
  print $count;
}

keep_track();
keep_track();
keep_track();

// output 123

I know that a static variable holds the value even after the function exits but in the above function I am assigning a value in the very first line, yet it still adding +1 with the previous value of $count.

Could you please explain this? (I am sorry if I sound like a stupid.. but I am trying to find out how exactly this happening)

Upvotes: 2

Views: 114

Answers (2)

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

The code static $count = 0; is executed once upon compilation which is why with each call of your function the value is not overwritten. See the note "Static declarations are resolved in compile-time." at http://www.php.net/manual/en/language.variables.scope.php

Upvotes: 3

karthikr
karthikr

Reputation: 99680

$count is initialized only in first call of function and every time the method is called, it increments $count.

In this link, scroll down to Using static variables for a better understanding.

Upvotes: 4

Related Questions