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?

Alex
  • 66,732
  • 177
  • 439
  • 641
  • You have to elaborate; currently it does not make much sense. How do you plan to get the name? From the value of `$id`? And *why* do you need the name of the constant? What are you going to do with that name? – knittl Jul 28 '12 at 09:48
  • The function signature implies you need to pass the value of the constant, but the function body only works right when the *name* of a constant is passed. When you call that function with no arguments, you're basically asking "is `self::1` defined?", which is surely not what you want. – DCoder Jul 28 '12 at 09:48
  • yes, that was a bad attempt to get the constant :( Anyway I still want to get the name.. (and check if its defined) – Alex Jul 28 '12 at 09:49
  • And I'm not sure if you checked stackoverflow. http://stackoverflow.com/questions/1880148/how-to-get-name-of-the-constant and http://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class. -1 for not reading these ones. – verisimilitude Jul 28 '12 at 09:53

3 Answers3

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;
    }
}
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());
verisimilitude
  • 5,077
  • 3
  • 30
  • 35
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()
Community
  • 1
  • 1
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
  • 1
    The link you gave is pointing to a question about the C# language, not PHP language. And your answer doesn't look like valid PHP code. – Jocelyn Jul 28 '12 at 10:06