1

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?

alexw
  • 8,468
  • 6
  • 54
  • 86

1 Answers1

0
   public static function setMessageStream(&$stream){
        static::$_message_stream = $stream;
    }

Should in fact be

   public static function setMessageStream(&$stream){
        self::$_message_stream = $stream;
    }

Notice the self.

Also,

public static function addMessage($type, $message){
    $alert = [
        "type" => $type,
        "message" => $message
    ];
    static::$_message_stream[] = $alert;
}

Should again be:

public static function addMessage($type, $message){
    $alert = [
        "type" => $type,
        "message" => $message
    ];
    self::$_message_stream[] = $alert;
}

You should also be aware that since you're assigning by reference, you will modify the actual value of the variable(so far it's not the case, just pointing it out for future reference.)

Andrei P.
  • 302
  • 3
  • 9