Forum : How do I get a variable in a function to retain its value between calls?
Brief description  about Online courses   join in Online courses
View prabeen  patra 's Profile

How do I get a variable in a function to retain its value between calls?

How do I get a variable in a function to retain its value between calls???
Asked by prabeen patra | Mar 17, 2010 |  Reply now
Replies (1)
View teacher siliconindia 's Profile
Hi Prabeen,
The key here is to use the static keyword in your function declaration, so for instance:
<?php
function myfunc() { static $myfunctionvariable = 1;
echo "the number $myfunctionvariable\n";
$myfunctionvariable++;
}
myfunc(); //1
myfunc();//2
myfunc();//3
?>
The use of the static keyword means that it will only be assigned the value 1 once, so each time the function is called the number will increment by one. If you do not use the static keyword, each time the function is called the variable will be set back to 1 each time.
Copy the code and try calling the function a few times both with and without the static keyword to see the effect it has.
Mar 17, 2010