Hi! I'm making a CLI application and I need a global variable (array) which would be accessible throughout multiple tasks and classes. This variable needs to be instantiated once the main script starts running (my server), after which I need to add new items in different places inside the app. How would I do this?
I tried putting it in services, but since this service is a class I'm not sure how to make a unique instance of it and of the array inside of it. I've tried making this class in different ways, including static properties and functions and also this:
class OnlineUsers
{
private $onlineUsers = null;
public function getOnlineUsers() {
if ($this->onlineUsers == null) {
$this->onlineUsers = [];
}
return $this->onlineUsers;
}
public function addOnlineUser($user) {
array_push($this->onlineUsers, $user);
}
}
In services.php:
$di->setShared('onlineUsers', function () {
return new OnlineUsers();
});
But no matter how I create it, when adding to array (for example in ChatTask), it always adds one item (the last one), so I'm guessing it's being overwritten or the instance is not persistent even if MainTask is still running so the application is not "done". What am I doing wrong and is there a smarter way of doing what I need?
TL;DR: I'm just trying to have a single global variable that's accessible throughtout my CLI application (either as a plain array or as a class) which I can modify. Could you help me with this?