Question

I got this code at http://w3schools.com/php/php_variables.asp

The code is

<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

and the website claims that the output will be 012

No my question is whenever function myTest() runs then $x should be set to 0 and hence the output should be 000. Can someone tell me that why will running the function myTest() again and again increase the value, even though $x is again and again reset to the value of 0.

Please help me as I am a newbie. I tried asking a few people who know programming and they agreed with me that the output should be 000.

Was it helpful?

Solution

The output is right, it should be 012: http://codepad.org/NVbfDGY7

See this example in the official documentation: http://www.php.net/manual/en/language.variables.scope.php#example-103

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

test();  // set $a to 0, print it (0), and increment it, now $a == 1
test();  // print $a (1), and increment it, now $a == 2
test();  // print $a (2), and increment it, now $a == 3

The doc says:

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

OTHER TIPS

The website is right; the output will be 012 and not 000 in most of the programming languages if not all.

This is because variable is declared in memory once and will be reused when you call that function. It's what static is. I learned to understand this in C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top