views:

168

answers:

2

Assuming you have a constant defined in a class:

class Foo {
    const ERR_SOME_CONST = 6001;

    function bar() {
        $x = 6001;
        // need to get 'ERR_SOME_CONST'
    }
}

Is it possible with PHP?

+2  A: 

You can get them with the reflection API

I'm assuming you would like to get the name of the constant based on the value of your variable (value of variable == value of constant). Get all the constants defined in the class, loop over them and compare the values of those constants with the value of your variable. Note that with this approach you might get some other constant that the one you want, if there are two constants with the same value.

example:

class Foo {
    const ERR_SOME_CONST = 6001;
    const ERR_SOME_OTHER_CONST = 5001;

    function bar() {
        $x = 6001;
        $fooClass = new ReflectionClass ( 'Foo' );
     $constants = $fooClass->getConstants();

     $constName = null;
     foreach ( $constants as $name => $value )
     {
      if ( $value == $x )
      {
       $constName = $name;
       break;
      }
     }

     echo $constName;
    }
}

ps: do you mind telling why you need this, as it seems very unusual ...

Jan Hančič
Nothing serious, actually. Just thinking of the way to pass error code from class function. As for me const ERR_SOME_ERROR='ERR_SOME_ERROR' looks strange, i thought my getLastError() function could return something like array(5003=>'ERR_SOME_ERROR',5002=>'ERR_SOME_ERR2') and so on.Just to have error code and error name returned. Well, the more i think of it, i'll probably will not use it (for the unusual syntax as you told) :)
Deniss Kozlovs
+3  A: 

With Reflection:

$class = new ReflectionClass("Foo");
$constants = $class->getConstants();

$constants is an array which holds all the names and values of the constants defined in class Foo.

Davide Gualano