2

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!

2 Answers 2

0

It's better to hide its state from the outside, so:

static $messages;

Should be:

private static $messages = array();

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 (triggering E_STRICT warnings), e.g.

public static function yourFunction() { }
3
  • I made your changes to my file. Now I'm getting an error that says "Parse error: syntax error, unexpected '[' in messenger.class.php on line 8" Line 8: self::messages[] = $message;
    – Rohjay
    May 29, 2012 at 1:55
  • It should be self::$messages not self::messages
    – Ja͢ck
    May 29, 2012 at 1:56
  • Jack - you are the man! I don't typically work without an instance of a class so this is new territory for me. Works perfectly now; Thank you sir!
    – Rohjay
    May 29, 2012 at 1:59
0

I'm not entirely sure on what you are asking. Yes, what you are suggesting would work fine. But if you aren't aware, your syntax is a bit off.

public static function addMessage( $message ) { ... }
public static function showMessages() { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.