在php中获取类常量名称?

时间:2010-05-18 14:41:40

标签: php oop class-constants

我有一个带有一些类常量的php类,它们指示实例的状态。

当我使用该类时,在我运行一些方法之后,我会做一些检查以确保状态是我期望的。

例如,在调用某些方法之后,我希望状态为MEANINGFUL_STATUS_NAME

$objInstance->method1();
$objInstance->method2();
if ( $objInstance->status !==  class::MEANINGFUL_STATUS_NAME ) { 
    throw new Exception("Status is wrong, should not be " . class::MEANINGFUL_STATUS_NAME . ".");
}

然而,这给了我异常消息

"Status is wrong, should not be 2"

当我真正想要看到的是

"Status is wrong, should not be MEANINGFUL_STATUS_NAME"

所以我失去了常名的意义。我正在考虑制作一个“转换表”数组,所以我可以将常量值转换回它们的名称,但这看起来很麻烦。我该如何翻译,所以我收到一条错误消息,让我更好地了解出了什么问题?

3 个答案:

答案 0 :(得分:5)

这是一个棘手的解决方案:

$r = new ReflectionClass("YourClassName");
$constantNames = array_flip($r->getConstants());

$objInstance->method1();   
$objInstance->method2();   
if ( $objInstance->status !== YourClassName::MEANINGFUL_STATUS_NAME ) {    
    throw new Exception("Status is wrong, should not be " . $constantNames[YourClassName::MEANINGFUL_STATUS_NAME] . ".");   
} 

答案 1 :(得分:1)

现在我发现我可以使用字符串作为常量的值。我习惯看到数字。我不应该这样做,或者为什么这不起作用?

答案 2 :(得分:0)

另一种方法可能是让对象检查状态是否处于所需模式。

如果不是,则对象的方法可以抛出异常。

未经测试的例子:

class Klasse
{
    const WANTED_VALUE    =  1;
    const UNWANTED_VALUE  =  2;

    private static $constant_names  =  array();
    p... function __construct ()
    {
        if ( empty( self::$constant_names ) )
        {
            $class            =  new ReflectionClass( __CLASS__ );
            $constants        =  $class->getConstants();
            $constants        =  array_flip( $constants );// requires the constant's values to be unique
            self::$constants  =  $constants;
        }
    }
    public function checkNeededStatus ()
    {
        $needed_status  =  self::WANTED_VALUE;// could also be a parameter(an argument) with a default value
        if ( $this->status !== $needed_status )
        {
            $constant_name  =  self::$constants[ $this->status ];
            $message        =  'Status is wrong, '
                . 'should not be: `' . $constant_name . '`.'
            ;
            //$message .=  '(it should be `' . self::$constants[ $needed_status ] . '`)';
            throw new Exception( $message );
        }
    }
}

$objInstance  =  new Klasse();
$objInstance->method1();
$objInstance->method2();
$objInstance->checkNeededStatus();

信用:

考虑不使用Reflection可能会很好。 因为抛出的消息留在类中, 在不失去太多可维护性的情况下,这种情况变得更有可能。