How to get name of the constant?

44,984

Solution 1

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 ...

Solution 2

Here's what I did to achieve it. Inspired by Jan Hancic.

class ErrorCode
{
    const COMMENT_NEWCOMMENT_DISABLED = -4;
    const COMMENT_TIMEBETWEENPOST_ERROR = -3;
    /**
     * Get error message of a value. It's actually the constant's name
     * @param integer $value
     * 
     * @return string
     */
    public static function getErrorMessage($value)
    {
        $class = new ReflectionClass(__CLASS__);
        $constants = array_flip($class->getConstants());

        return $constants[$value];
    }
}

Solution 3

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.

Solution 4

All the other answers cover the essential points. But, if crazy one liners is your thing, then:

function getConstantName($class, $value)
{
    return array_flip((new \ReflectionClass($class))->getConstants())[$value];
}

If you need to handle the case where the value might not actually be one of the constants, then you can give up an extra line:

function getConstantName($class, $value)
{
    $map = array_flip((new \ReflectionClass($class))->getConstants());
    return (array_key_exists($value, $map) ? $map[$value] : null);
}

Solution 5

I know this is an old question and all, but I still feel that I have some useful input. I implemented this using an abstract class that all my enums extend. The abstract class contains a generic toString() method;

abstract class BaseEnum{
    private final function __construct(){ }

    public static function toString($val){
        $tmp = new ReflectionClass(get_called_class());
        $a = $tmp->getConstants();
        $b = array_flip($a);

        return ucfirst(strtolower($b[$val]));
    }
}

//actual enum
final class UserType extends BaseEnum {
    const ADMIN = 10;
    const USER = 5;
    const VIEWER = 0;
}

This way you can get a human readable string to use in output, on every enum that extends the base enum. Furthermore, your implementation of the enum, being final, cannot be extended and because the constructor in the BaseEnum is private it can never be instantiated.

So for instance, if you show a list of all usernames with their types you can do something like

foreach($users as $user){
    echo "<li>{$user->name}, ".UserType::toString($user->usertype)."</li>";
}
Share:
44,984
Deniss Kozlovs
Author by

Deniss Kozlovs

Web developer / freelancer

Updated on July 08, 2022

Comments

  • Deniss Kozlovs
    Deniss Kozlovs almost 2 years

    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?

  • Deniss Kozlovs
    Deniss Kozlovs over 14 years
    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) :)
  • Timo Huovinen
    Timo Huovinen over 10 years
    also needed it for CURLE_* constant support where curl_multi_strerror was not available
  • Populus
    Populus almost 10 years
    Just wanna say that this will not work if constants have the same value. Shouldn't be a problem most of the time, but yea...
  • Frug
    Frug about 9 years
    I "need" something like this in order to provide a nicer error output without having to rewrite how we track certain error codes that are stored as constants.
  • abdul rashid
    abdul rashid about 8 years
    This is Easy and Quick Solution. Flip the Array and check for the Key.
  • Stefanos Petrakis
    Stefanos Petrakis over 5 years
    That is not what the OP asked for.
  • DrKey
    DrKey almost 5 years
    I think this wouldn't work when a constant has an array as value as well..