如何检查方法调用是否使用有效的类常量


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

我有一个类,其中一个方法接受一个参数,该参数应该是一个特定范围的选项之一。我将这些选项定义为类中的常量。如何防止使用不是这些常量之一的值调用方法?

一些代码可能会使我想要达到的目标更清楚:

<?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

使用ReflectionClass的getConstants()方法:

public function go($option)
{
    $r = new 'ReflectionClass($class);
    if (in_array($option, $r->getConstants()) {
        echo 'You chose: ' . $option;
    } else {
        echo 'urgh';
    }
}