PHP maintain class state
<p>I'd like to have a library class that maintains state across the same request. My use case is that I want to pass 'messages' to the class, and then call them at any time from a view. Messages can be added from any part of the application.</p>

<p>I had originally done this via static methods, which worked fine. However, as part of the lib, I also need to call <code>__construct</code> and <code>__destruct()</code>, which can't be done on a static class.</p>

<p>Here's a very simple example of what I am trying to do:</p>

<pre><code>class Messages
{
  private static $messages = array();

  public function __construct()
  {
    // do something
  }

  public function __destruct()
  {
    // do something else
  }

  public static function add($message)
  {
    self::$messages[] = $message;
  }
  public static function get()
  {
    return self::$messages;
  }
}
</code></pre>

<p>I can then add messages anywhere in my code by doing</p>

<pre><code>Messages::add('a new message');
</code></pre>

<p>I'd like to avoid using static if at all possible (testability). I have looked at DI, but it doesn't seem appropriate, unless I'm missing something. </p>

<p>I could create a class (non-static) instead, but how do I then ensure that all messages are written to the same object - so that I can retrieve them all later?</p>

<p>What's the best way to tackle this?</p>
