Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to enum types in PHP5?

Tags:

php

enums

I have one PHP5 object passing messages to another, and would like to attach a type to each message. For example, MSG_HOT, MSG_WARM, and MSG_COLD. If PHP5 had an enum type, I would probably use that to define the message types, but (unless I'm mistaken) there is no such animal. I've looked at a few options:

Strings ('MSG_HOT', 'MSG_WARM', and 'MSG_COLD') are bad because I would inevitably type something like 'MSG_WRAM' and things would break. Numbers suffer the same problem and are also less clear.

Defines work:

define('MSG_HOT', 1);
define('MSG_WARM', 2);
define('MSG_COLD', 3);

but pollute the global namespace, and thus would require more verbose names to ensure uniqueness. I'd prefer not to have my code littered with things like APPLICATIONNAME_MESSAGES_TYPE_HOT.

Finally, I could use class names to distinguish types, like so:

class MessageHot extends Message {}
class MessageWarm extends Message {}
class MessageCold extends Message {}
class Message
{
    public function Type()
    {
        return get_class($this);
    }
    public function Data()
    {
        return $this->data;
    }
    public function __construct($data)
    {
        $this->data = $data;
    }
    private $data;
}

This is good, I think, but is also a lot of work for what seems like it ought to be a simple concept.

Am I missing a better alternative?

like image 505
Brian Avatar asked Jul 26 '09 20:07

Brian


2 Answers

You could use class constants:

class Message
{
    const hot = 0;
    const warm = 1;
    const cold = 2;
}

foo(Message::hot);
foo(Message::warm);
foo(Message::cold);
like image 60
Greg Avatar answered Oct 21 '22 10:10

Greg


A very common convention is to use class constants in PHP.

e.g.

class Message
{
    const HOT  = 0;
    const WARM = 1;
    const COLD = 2;
}
like image 27
hobodave Avatar answered Oct 21 '22 10:10

hobodave