I have a PHP class with a static variable that is initialized to 0.
In my index.php file, I'm using Spatie's Async to call functions from other classes (a few classes deep), which increment the previously mentioned static variable (I also tried using a singleton pattern, and PHP's $GLOBALS variable). When that's done, I call the Spatie's pool->wait() function, and then print / log the static variable. This always gives me 0. If I log the variable right after I increment it, then it gives me 1, as if the variable is being initialized again for each function call.
The code is far too complex to display it nicely here, so I hope that I explained it detailed enough.
Is there any way I can get a variable with a proper global scope?
EDIT: As requested, I'm adding some code snippets, but with some of the class & variables changed to generic ones for simplicity's sake.
This is the PHP class where the variable is initialized, there is nothing interesting here, the variable isn't used here afterwards:
class ClassOne
{
static $var = 0;
...
}
This is the class where the functions are called, in index.php it's of course instantiated and it's 'func' function is called:
class ClassTwo
{
protected $pool;
public function __construct()
{
// The Pool object is from the PHP Spatie Async library.
$this->pool = Pool::create();
}
public function func (array $data) {
foreach ($data as $datum) {
for($iteration = 0; $iteration < $datum['iterations']; $iteration++) {
$this->pool->add(function () use ($datum) {
$instance = new ClassThree();
$instance->call($datum['data']);
})->then(function ($output) {
...
})->catch(function (Exception $exception) {
...
});
}
}
$this->pool->wait();
print 'Variable: ' . ClassOne::$var;
}
...
}
Lastly, these are the functions where the variable is incremented, the variable isn't touched anywhere else here:
class ClassThree
{
public function call($data) {
try {
...
ClassOne::$var++;
} catch {
...
}
}
}
As I mentioned earlier, were I to put the 'print' from ClassTwo right after the increment in ClassThree, I would get 1 several times, but this way I get 0.