Static Variable in PHP

Introduction

In this article I will explain static variables in PHP. A static variable is a variable that has been allocated statically. Static variables only exist within a local scope and it retains its previous value even after function calls; static variables are initialized only one. Static variables can be used wiih recursive functions.

Example

Static Variable with Recursive Function

<?php

function test()

 {

  static $count=0;

    $count;

     return $count;

     if($count<10)

     {

       test();

     }

     $count--;

 }

?>

This example does not return a value.

Declare Static Variable

<?php

function foo()

{

static $int=0;

//correct

static $int=1+2;

//wrong(as it is an expression)

static $int = sqrt(121);

//wrong(as it is an expression too)

$int++;

echo $int;

}

?>

Example2

<?php

function testfun()

{

    static $value = 0;

    $value += 1;

    return $value;

}

testfun();

testfun();

testfun();

testfun();

echo testfun() ."<br>";

?>

In the example above, I have used a simple non-static variable and incremented the variable each time the function is called. We call the function five times. After five function calls $value is equal to 1.

Output

static variable.jpg

The static variable function is initialized only one time, when the function is the first called. They retain their value afterwards.

Example

<?php

function staticf()

 {

    static $value = 0;

    $value += 1;

    return $value;

}

staticf();

staticf();

staticf();

staticf();

echo staticf(). "<br>";

?>

Output

static variable.jpg

After five consecutive calls $value is equal to 5.


Similar Articles