Как получить название константы?

Это сводится к тому, что Вы используете в классе.

, Если лаборатории и присвоения находятся в Linux, то Вы, вероятно, хотите решение MinGW. Если они находятся в окнах, получают Visual Studio Express.

49
задан Deniss Kozlovs 10 December 2009 в 00:45
поделиться

2 ответа

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

57
ответ дан 7 November 2019 в 11:27
поделиться

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.

13
ответ дан 7 November 2019 в 11:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: