Reputation: 7990
I have a class where one method accepts an arguments that should be one of a specific range of options. I have defined these options as constants within the class. How do I prevent the method being called with a value that is not one of these constants?
Some code might make it clearer what I'm trying to achieve:
<?php
class Foo
{
const OPTION_A = 'a valid constant';
const OPTION_B = 'another valid constant';
public function go( $option )
{
echo 'You chose: ' . $option;
}
}
$myFoo = new Foo();
$myFoo->go( Foo::OPTION_A ); // ok
$myFoo->go( Foo::OPTION_B ); // ok
$myFoo->go( 'An invalid value' ); // bad - string, not one of the class constants
$myFoo->go( Bar::OPTION_A ); // bad - constant is not local to this class
Upvotes: 1
Views: 42
Reputation: 7011
Use ReflectionClass's getConstants() method:
public function go($option)
{
$r = new \ReflectionClass($class);
if (in_array($option, $r->getConstants()) {
echo 'You chose: ' . $option;
} else {
echo 'urgh';
}
}
Upvotes: 1