I’m looking for a syntactical win here… I want to be able to add messages into a singleton class to be retrieved later.
Currently it looks like this:
class messenger
{
static $messages;
public function addMessage( $message ) {
self::messages[] = $message;
}
public function showMessages() {
foreach ( self::messages as $message ) {
echo "<p>$message</p>";
}
}
}
Now I want to be able to use it like this:
messenger::addMessage( 'This is a potential message!' );
messenger::addMessage( 'Another potential message!' );
messenger::showMessages();
Which would output this ([p] == an html paragraph tag):
[p]This is a potential message![/p]
[p]Anotherpotential message![/p]
Am I off base with the concept? I really don’t want to have to re-associate it with a variable in each different class it’s used in, but I’m not sure if my hang-up is “how to do it” or if it’s simply not possible.
The concept is to be able to add error messages into this (like an array) that I don’t have to globalize and can retrieve later.
EDIT: I’m doing this so that through my framework, I can add messages to this class from other classes that might also want to display errors at a later time without having to use globals or re-instantiate the class.
Thanks for your help!
It’s better to hide its state from the outside, so:
Should be:
Also note the initialization to make sure it’s an array before you add messages into it.
Furthermore, the methods you’re using should be declared as
static, otherwise PHP will complain about this (triggeringE_STRICTwarnings), e.g.