Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is php static variable resetting ignored when a function is recalled?

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.

like image 348
Rahina Rakhi Avatar asked Jul 05 '26 06:07

Rahina Rakhi


2 Answers

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.

like image 123
Nabil Kadimi Avatar answered Jul 06 '26 19:07

Nabil Kadimi


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++.

like image 35
Touch Avatar answered Jul 06 '26 21:07

Touch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!