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.
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.
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.
counter += 1 to MyClass. counter += 1 so the CLASS-counter variable is incremented - not the INSTANCE-copy of that value.
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 ::.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With