Best Practices: How to check for a constant in an array using PHP? -
I'm not sure how to do this. I have an object and I want to set this a 'type' property, but before I want to check it to make sure it's a valid type.
I was thinking that it is a good time to experiment, since the stable names, the constant will not change (nor do I want them).
// This is just a sample that I was thinking: Class Fobar {const TYPE_1 = 'Type 1'; Protected $ _types = array (auto :: TYPE_1); Public function settap ($ value) {// check is to ensure that the value is a valid type / I am thinking that it will accept // Foobar :: TYPE_1, 'TYPE_1', or 'type 1' // Should be able to flexibility but I do not know}} $ foobar = new Foobar (); $ Foobar- & gt; SetType ('TYPE_1'); // What should go here? (Best practice)
Update: I decided that I do not need to use constants in the first place, but I have accepted an answer I think if you have an array of all types, then / code >, Then you can check directly what is the value in it: But to ensure this type of array requires additional work that all types of types are in the array, along with it $ _ types
class Foobar {const TYPE_1 = 'type 1'; ## Declare all available types as stable variables ## Do not forget to change it when new type will be protected static $ _types = array (self :: TYPE_1); Public function set type ($ value) {if (in_array ($ value, self :: $ _ types)) {// type is valid, we can use it} Other {// typed wrong, reporting error new exceptions ( "Wrong type [" $ value. "]"); }}}
still
therefore the only copy of the data will be used for all instances.
Comments
Post a Comment