make money free online
star business online
11:39 PM

Static Variables

Posted by Business

The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.

You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name. STATIC $somevar;

Consider an example:

function keep_track() {

STATIC $count = 0;

$count++;

print $count;

print "
";

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

What would you expect the outcome of this script to be? If the variable $count were not designated to be static (thus making $count a local variable), the outcome would be:

1
1
1

However, since $count is static, it will retain its previous value each time the function is executed. Therefore, the outcome will be:

1
2
3

0 comments:

Post a Comment