如何获取常量的名称?

时间:2012-07-28 09:42:52

标签: php constants

const

  STUFF      = 1,
  MORE_STUFF = 3,
  ...
  LAST_STUFF = 45;  


function($id = self::STUFF){
  if(defined('self::'.$id)){
    // here how do I get the name of the constant?
    // eg "STUFF"
  }
}

我可以在没有大量案例陈述的情况下得到它吗?

3 个答案:

答案 0 :(得分:3)

查看ReflectionClass::getConstants

类似的东西(它非常丑陋且低效,顺便说一下):

class Foo {
    const

      STUFF      = 1,
      MORE_STUFF = 3,
      ...
      LAST_STUFF = 45;     

    function get_name($id = self::STUFF)
    {
         $rc = new ReflectionClass ('Foo');
         $consts = $oClass->getConstants ();

         foreach ($consts as $name => $value) {
             if ($value === $id) {
                 return $name;
             }
         }
         return NULL;
    }
}

答案 1 :(得分:2)

您可以使用[Reflection][1]

假设你有以下课程。

class Profile {
    const LABEL_FIRST_NAME = "First Name";
    const LABEL_LAST_NAME = "Last Name";
    const LABEL_COMPANY_NAME = "Company";
}


$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());

答案 2 :(得分:1)

PHP:

  1. 使用您的班级名称
  2. 中的ReflectionClass
  3. 使用getConstants()方法
  4. 现在您可以扫描getConstants()结果并验证获取目标名称的结果值
  5. ========================================

    C#

    你的答案来自 Jon Skeet

    Determine the name of a constant based on the value

    或者使用enume(将enume name转换为string很简单:)

    public enum Ram{a,b,c}
    Ram MyEnume = Ram.a;
    MyEnume.ToString()
    
相关问题