I’m not really sure how to do this. I have an object and I want to set a ‘type’ property on it, but before doing that I want to check to make sure it’s a valid type.
I was thinking this is a good time to use constants since the type names won’t change (nor do I want them to be).
// this is just a sample of what I was thinking:
class Foobar
{
const TYPE_1 = 'type 1';
protected $_types = array(
self::TYPE_1
);
public function setType($value)
{
// check to make sure value is a valid type
// I'm thinking it should be able to accept
// Foobar::TYPE_1, 'TYPE_1', or 'type 1'
// for flexibility sake. But I don't know
}
}
$foobar = new Foobar();
$foobar->setType('TYPE_1'); //what should go here? (best practice)
Update: I decided I didn’t really need to use constants in the first place, but I’ve accepted an answer that I think could have gotten the job done.
If you have an array with all types
$_types, then you can directly check if value presents in it:But it require additional work to support this array to make sure that all posible types are in array. Also it should be
static. So the only copy of data will be used for all instances.