【问题标题】:Get class constant names in php?在php中获取类常量名称?
【发布时间】:2011-02-20 22:40:00
【问题描述】:

我有一个 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"

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

【问题讨论】:

标签: php oop class-constants


【解决方案1】:

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

$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] . ".");   
} 

【讨论】:

    【解决方案2】:

    现在我突然想到我可以使用字符串作为常量的值。我习惯看数字。我是否有理由不这样做,或者为什么这不起作用?

    【讨论】:

    • 您将答案标记为解决方案,但...您的答案是一个问题 :)
    • @vectorialpx 我宁愿说这个答案提示了一个新的问题/问题,超出了原来的范围。
    【解决方案3】:

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

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

    未经测试的例子:

    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();
    

    学分:

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

    【讨论】:

      猜你喜欢
      • 2013-09-16
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2016-02-02
      • 2020-12-20
      • 2021-08-19
      相关资源
      最近更新 更多