I am trying to design a class that will have a static "message stream" to which its instances can read and write. This message stream must be an external variable, because (usually) it will be a $_SESSION variable. The idea is like this:
class Streamer {
protected static $_message_stream = null; // A message stream (array)
public function __construct(){
// Blah blah blah
}
/* Set a message stream, usually a global or session variable. */
public static function setMessageStream(&$stream){
static::$_message_stream = $stream;
}
/* Add a session message to the session message stream */
public static function addMessage($type, $message){
$alert = [
"type" => $type,
"message" => $message
];
static::$_message_stream[] = $alert;
}
}
As you can see, setMessageStream accepts a reference parameter. Typical use case would be something like:
// Do this in a global configuration file
session_start();
$_SESSION['userAlerts'] = [];
Streamer::setMessageStream($_SESSION['userAlerts']);
// This would happen in a specific context
Streamer::addMessage("foo", "bar");
print_r($_SESSION['userAlerts']);
I expect the output to be Array("foo" => "bar"). Instead, I get an empty array. Why doesn't this work?
Update: This is indeed the same issue as in Static variable inside function can't hold reference to singleton.
So, that explains the "why". How could I modify my design to achieve the desired behavior? Specifically, how can I allow a class to statically "register" a given external variable for R/W access?