PHP experts tell me a static variable within a function?
Doesn’t make any sense. A function is not part of a class or object, so is already ‘static’.
Its a type of variable that will retain its value even when program execution goes out of block scope.
Best if you read it for yourself here:
function foo() {
static $i=0;
echo '<p>foo has been called ',($i++),' times<p>';
}
foo();
foo();
foo();
Means of having a function or method store state. If that is the case though generally it is better to use a object or composition.
(Agrees it is good to read it for yourself as well, but can be a bit confusing for a beginner).
Basically a static variable is a variable which has a persistent value (it doesn’t go away when the function does), though it’s only available within that function.
For example, if I do something like:
<?php
// Example from there site.
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
$a is set to zero on the first call to test() (and only the first call). Afterwards, each additional call will do the rest of that function, so $a’s value will go up every time.
It’s essentially the same as a global variable, except it can only be called from within the function it was created (if that helps at all).
I sit corrected…
=p
In just about anything else it would have made no sense. I forgot PHP had function-scope static variables until this post.