1
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"
  }
}

Can I get it without a huge case statement?

4

3 回答 3

3

Have a look at ReflectionClass::getConstants.

Something like (it's pretty ugly and inefficient, btw):

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;
    }
}
于 2012-07-28T09:50:43.190 回答
2

You can use the [Reflection][1] for this.

Assuming you have the below class.

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());
于 2012-07-28T09:50:57.210 回答
1

PHP:

  1. Use ReflectionClass from your class name
  2. Use getConstants() method
  3. now you can scaning getConstants() results and verify result values for getting the target name

========================================

C#

Your answer is here by Jon Skeet

Determine the name of a constant based on the value

Or use enume (converting enume name to string is easy:)

public enum Ram{a,b,c}
Ram MyEnume = Ram.a;
MyEnume.ToString()
于 2012-07-28T09:59:46.243 回答