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?
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);
A very common convention is to use class constants in PHP.
e.g.
class Message
{
const HOT = 0;
const WARM = 1;
const COLD = 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With