I am using the PHP-CPP library to develop PHP extensions.
When I try the following in C++:
#include <phpcpp.h>
static int number=0;
Php::Value get_num()
{
number++;
return number;
}
And the following in PHP:
<?php
echo get_num();
?>
Everything works as expected for awhile, but then the "number" variable randomly resets back to zero. Also, pressing CTRL+F5 in Firefox, the "number" variable again resets back to zero.
How do I avoid "number" from resetting?
A global C++ variable in a PHP extension is not persistent.
It all depends on the setup of your webserver. If you use Apache for example (and most others have a similar setup), there are multiple instances of the webserver process running, all serving pageviews. Each of these instances has its own global 'number' variable. That's why you do not see the number incrementing as you had expected: not every pageview is served by the same Apache instance.
On top of that: when the load of your webserver goes up or goes down, new Apache processes are started and stopped, and new 'number' variables are created with an initial value of 0. Also, an Apache process normally restarts after a certain fixed number of pageviews (set in the apache configuration file), which also sets the counter back to zero.
In your own small testing environment, you do not run into this problem that fast, because the load is so low that it can all be handled by a single instance of the webserver, but on a live busy server you will certainly encounter this.
If you want to use a persistent counter, you will have to store it somewhere else, for example in a file or database.