This question bugged me for years now and can't seem to find good solution still. I working in PHP and Java but it sounds like this maybe language-agnostic :)
Say we have a standard status reference table that holds status ids for some kind of entity. Further let's assume the table will have just 5 values, and will rem开发者_如何学Cain like this for a long time, maybe edited occasionally with addition of a new status. When you fetch a row and need to see what status it is you have 2 options(as I see it at least) - put it straight ID values(magic numbers that is) or use a named constant. Latter seem much cleaner, the question though is where those named constants should leave? In a model class? In a class that uses this particular constant? Somewhere else?
It sounds like what you're wanting to do is an enumerated value.
This is a value that has a literal name mapped to a constant value, this would be something like
Statusone = 1
Statustwo = 2
Then anywhere in your program you could refrenece statusone which the compiler would see as 1.
I'm not sure if this exists in php but I'm pretty sure it does in java
EDIT In response to some comments
I would typically put enumerated values in some kind of global namespace, or if you only need them when you are using that class spefically you can put them at the class level.
精彩评论