Local variables within functions have a short life. They last until the execution is finished. Sometimes, you want to give a function a memory. This is where the static keyword is used to retain the value of the variable between function calls. This means that the function "remembers" the value of the variable from execution to execution.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>Static Variables</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php function counter() { static $counter = 0; $counter++; return $counter; } echo "Current counter: ", counter(), "<br />"; echo "Current counter: ", counter(), "<br />"; echo "Current counter: ", counter(), "<br />"; echo "Current counter: ", counter(), "<br />"; echo "Current counter: ", counter(), "<br />"; ?> </p> </body> </html> |