如何获得常量的名称? [英] How to get name of the constant?

查看:155
本文介绍了如何获得常量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你在类中定义了一个常量:

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'
    }
}

推荐答案

您可以使用反射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.

例如:

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:你介意为什么需要这个,因为它似乎非常不寻常...

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

这篇关于如何获得常量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆