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?