PHP5 中枚举类型的替代方案?
我有一个 PHP5 对象将消息传递给另一个对象,并且想为每条消息附加一个类型。 例如,MSG_HOT
、MSG_WARM
和 MSG_COLD
。 如果 PHP5 有枚举类型,我可能会用它来定义消息类型,但是(除非我弄错了)没有这样的动物。 我研究了几个选项:
字符串('MSG_HOT'
、'MSG_WARM'
和 'MSG_COLD'
)很糟糕,因为我会不可避免地要输入像 'MSG_WRAM'
这样的东西,事情就会崩溃。 数字也面临着同样的问题,而且也不太清晰。
定义工作:
define('MSG_HOT', 1);
define('MSG_WARM', 2);
define('MSG_COLD', 3);
但会污染全局命名空间,因此需要更详细的名称来确保唯一性。 我不希望我的代码中充满诸如 APPLICATIONNAME_MESSAGES_TYPE_HOT
之类的内容。
最后,我可以使用类名来区分类型,如下所示:
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;
}
我认为这很好,但对于看起来应该是一个简单的概念来说,这也需要做很多工作。
我错过了更好的选择吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个非常常见的约定是在 PHP 中使用类常量。
例如
A very common convention is to use class constants in PHP.
e.g.
我还为此使用了带有常量的类。 我添加以下内容
实现静态 __toString() 方法来执行前面的操作
我还可以使用 Message::$enums 来测试变量:
I also use a class with consts for this. I add the following
implement a static __toString() method to do the previous
I can also use the Message::$enums to test variables:
您可以使用类常量:
You could use class constants:
您可能想查看 stackoverflow 上这个问题的前两个答案
提到了
You might want to look at the two first answers to this question on stackoverflow
mentionning both
创建抽象类 Enumerator:
声明您的枚举:
使用:
输出:
Make abstract class Enumerator:
Declare your enumerations:
Use:
Output: