sadia mallick February 2016

static variable not incrementing on function calling

function genTokenNo()
{
    static $i=0;
    $i=$i+1;
    return str_pad($i, 5, '0', STR_PAD_LEFT);
}

When I calls this function in other file the function doesn't returns unique value (an incremented value). Also while I echo this function in same file(where the function is made) it works fine. I know the concept of scope of static variable as I have already tried this by replacing $i by $_SESSION['i'] but no expected result. Thanks in advance.

Answers


Zbynek Vyskovsky - kvr000 February 2016

Note the value of $i is not persisted. So whenever you run new request to the server, the script is reloaded and $i is reset to 0.

To persist the variable in the per-user session use $SESSION['i'] but as you already tried, this will be unique per session, not globally.

To have globally unique number you need to store on the disk, using fopen/flock/fread/fwrite/fclose functions.


swaroop suthar February 2016

when function exists then lost the value of static variable

if(isset($_SESSION['i']))
   $_SESSION['i']++;
else
   $_SESSION['i']=0;


Sougata February 2016

For a single request it should work fine -

function genTokenNo()
{
    static $i=0;    
    $i=$i+1;
    return str_pad($i, 5, '0', STR_PAD_LEFT);
}

echo genTokenNo() . ' - ' . genTokenNo() . ' - ' . genTokenNo();

Output

00001 - 00002 - 00003

But if you are requesting multiple times then the value will be reset on every request and every time the response will be the same. I would suggest to store the value in database or some file. In this case using seesion woludn't be reliable.


Kausha Mehta February 2016

Your structure will look like below:

file1.php

function genTokenNo()
{
    static $i=0;
    $i=$i+1;
    return str_pad($i, 5, '0', STR_PAD_LEFT);
}

file2.php

include('file1.php');
//^^^^^^^^^^^^^^^^^^^ Include file before call that function.

echo genTokenNo(); //00001
echo "<br />";
echo genTokenNo(); //00002
echo "<br />";
echo genTokenNo(); //00003
echo "<br />";
echo genTokenNo(); //00004


sadia mallick February 2016

file1.php

<?php
    function genTokenNo()
    {
        static $i=0;
        $i=$i+1;
        return str_pad($i, 5, '0', STR_PAD_LEFT);
    }
?>

file2.php

<?php
include('file1.php');
$sql = "INSERT INTO table SET TokenNo='".genTokenNo()."' ";
mysql_query($sql);
?>

Post Status

Asked in February 2016
Viewed 3,892 times
Voted 10
Answered 5 times

Search




Leave an answer