voidstate voidstate - 2 years ago 93
PHP Question

How to Check Whether a Method Call Uses a Valid Class Constant

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:

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

Answer Source

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';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download