I have a question in my todays Exam in which I have to determine the output.
<?php
function statfun($x)
{
static $count=0;
$count += $x;
if ($count < 20) {
echo "$count <br>";
statfun(++$x);
} else {
echo "last num is $count";
}
}
statfun(2);
?>
The output is
2
5
9
14
last num is 20
I dont know why this is the output. I know it is due to the static member but each time it comes into the function the member $count is re-initialized.I had saw the documentation at Static Keyword.
But there is nothing written regarding the re-initialization of static variable? Can we re-initialize the static variable in PHP? With the same or any other value?
each time it comes into the function the member $count is re-initialized
This is incorrect. Static variables are initialized only once which is how statically declared variables differ from "ordinary" variables. So basically, you're assigning an initial value to $count. In multiple calls to statfun(), this static variable's value is preserved and can be reused.
From the manual, section "Using static variables":
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Also look at the example-code in the manual. The difference stated there should answer your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With