Generally, when the function completes its execution the variable data is deleted automatically by a php script. But sometimes we require those data to continue on another job. In such case, you can use a static variable to do the job.

By using the static keyword when you first declare the variable will keep the script running even after the code is executed.

Example code:

[php]<?php
function mddir() {
static $x = 5;
echo $x;
$x++;
}
mddir();
echo "<br>";
mddir();
echo "<br>";
mddir();
?> [/php]

The code will produce below result.


5
6
7

In the above code, we have a simple function with the static variable $x that has value 5. Also, in the echo statement, we have asked php script to auto-increment the value by one.

Once it is executed the script will use the static variable to display the outcome.

Related Posts

Leave a Reply