Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php static variable

/*
  1) Example demonstrating need for static variables
  This function is quite useless since every time it is called 
  it sets $a to 0 and prints 0. 
  The $a++ which increments the variable serves no purpose 
  since as soon as the function exits the $a variable disappears.
  To make a useful counting function which will not lose track of the current count, 
  the $a variable is declared static:
*/
function test()
{
    $a = 0;
    echo $a;
    $a++;
}

/*
  2) Example use of 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.
*/
function newTest()
{
    static $a = 0;
    echo $a;
    $a++;
}
 
PREVIOUS NEXT
Tagged: #php #static #variable
ADD COMMENT
Topic
Name
3+2 =