Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable not incrementing on function calling

Tags:

php

static

token

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.

like image 826
sadia mallick Avatar asked Feb 08 '16 11:02

sadia mallick


People also ask

Can a static variable increment?

Using a static variable will create one copy of the count variable which will be incremented every time an object of the class is created. All objects of the Counter class will have the same value of count at any given point in time.

Can we increment static variable in C?

Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

How do you increment a static variable in Python?

counter += 1 to MyClass. counter += 1 so the CLASS-counter variable is incremented - not the INSTANCE-copy of that value.

How do you call a static member function?

Static Function Members By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.


1 Answers

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.

like image 196
Zbynek Vyskovsky - kvr000 Avatar answered Sep 28 '22 11:09

Zbynek Vyskovsky - kvr000