php 如何获取常量的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1880148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get name of the constant?
提问by Deniss Kozlovs
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?
可以用 PHP 吗?
回答by Jan Han?i?
You can get them with the reflection API
您可以使用反射 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 ...
ps:你介意告诉你为什么需要这个,因为它看起来很不寻常......
回答by deathemperor
Here's what I did to achieve it. Inspired by Jan Hancic.
这是我为实现它所做的。灵感来自 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];
}
}
回答by Davide Gualano
With Reflection:
带反射:
$class = new ReflectionClass("Foo");
$constants = $class->getConstants();
$constantsis an array which holds all the names and values of the constants defined in class Foo.
$constants是一个数组,其中包含类 Foo 中定义的常量的所有名称和值。
回答by rael_kid
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;
我知道这是一个老问题,但我仍然觉得我有一些有用的意见。我使用我所有枚举扩展的抽象类来实现这一点。抽象类包含一个通用的 toString() 方法;
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 BaseEnumis privateit can never be instantiated.
通过这种方式,您可以在扩展基本枚举的每个枚举上获得一个人类可读的字符串以用于输出。此外,你的枚举的实施,正在final,不能延长,因为在构造函数BaseEnum是private它不能被实例化。
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>";
}
回答by bishop
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);
}
回答by Kevin
All constant can be assigned to an array using this function.
可以使用此函数将所有常量分配给数组。
$const = get_defined_constants();
then using following function you can print the array structure
然后使用以下函数可以打印数组结构
echo "<pre>";
print_r($const);
and you can see more explanation here www.sugunan.com
你可以在这里看到更多的解释www.sugunan.com
回答by jave
Warning: This way you should NOT program... ( if youre not sure what youre doing :) )
警告:这样你不应该编程......(如果你不确定你在做什么:))
I wrote 1 row which echos constants and their numeric values by your choice of CATEGORY_
我写了 1 行,通过您选择的 CATEGORY_ 来回显常量及其数值
so here is the list of CATEGORY_ ERR_
所以这里是 CATEGORY_ ERR_ 的列表
foreach(get_defined_constants() as $key => $value) if(strlen($key)>5) if(substr($key, 0,5)=="ERR_") echo"<br>Found an php ERR_ constant! : ".$key."=>".$value;
And if you want just the one youre looking for by number => I created 1row function:
如果您只想要按编号查找的那个 => 我创建了 1row 函数:
//input parameters: CATEGORYNAME_ , #constantNumber
function getConstantName($category,$constantNumber){foreach(get_defined_constants() as $key => $value) if(strlen($key)>strlen($category)) if(substr($key, 0,strlen($category))==$category) if($value==$constantNumber) return $key; return "No constant found.";}
So for example some info constant with number 64:
例如,一些数字为 64 的信息常量:
echo "NameOfConstant: ".getConstantName("INFO_",64);
will output something like: NameOfConstant: INFO_LICENSE
将输出类似: NameOfConstant: INFO_LICENSE
回答by Forseti
OK, OK, I know everything is already covered :) But Jan Han?i? asked for use case, so I'll share mine. Aside: everyone seems to use array_flip(). Why not array_search()?
好的,好的,我知道一切都已经涵盖了:) 但是 Jan Han?我?要求用例,所以我会分享我的。旁白:每个人似乎都在使用 array_flip()。为什么不是 array_search()?
I needed it in a class that extends \Exception and is base class of small set of my concrete exceptions. Each of those concrete exception classes covers a broad exception domain and has defined several precise exception causes. Reason? I don't want to have a horde of exceptions to maintain and remember of. Also, there is exception handler set that dumps exception's guts into log file - and it's here I need to get the constant name as trying to decipher exception cause from status in quite painful.
我在一个扩展 \Exception 的类中需要它,它是我的具体异常的一小部分的基类。这些具体的异常类中的每一个都涵盖了广泛的异常域,并定义了几个精确的异常原因。原因?我不想有一大群异常需要维护和记住。此外,还有一个异常处理程序集可以将异常的内脏转储到日志文件中 - 在这里我需要获取常量名称,因为试图从状态中破译异常原因非常痛苦。
Examples from my CLI scripts:
我的 CLI 脚本中的示例:
class AbstractException extends Exception {
public function getName() {
return array_search($this->getCode(), (new ReflectionClass($this))->getConstants());
}
}
class SyntaxException extends AbstractException {
const BAD_SYNTAX = 90;
const REQUIRED_PARAM = 91;
const REQUIRED_VALUE = 92;
const VALUE_TYPE = 93;
const VALUE_OUT_OF_BOUNDS = 94;
public function __construct ($message = "", $code = self::BAD_SYNTAX, Exception $previous = NULL) {
$script = basename($GLOBALS['argv'][0]);
echo "Invalid syntax: $message \nSee: `$script --help` for more information\n";
parent::__construct($message, $code, $previous);
}
}
// in autoload include
set_exception_handler(function(Exception $e) {
error_log(basename($GLOBALS['argv'][0]) . ';'. date('Y-m-d H:i:s') .';'. $e->getName() .';'. $e->getMessage() .';'. $e->getFile() .';'. $e->getLine() ."\n", 3, 'error.log');
exit ($e->getCode());
});
回答by Andrés Sendra
if you need to get the constant value on a method of the same class, you just need to use the self operator. You could use reflection if you want to use the constants on another class
如果你需要在同一个类的方法上获取常量值,你只需要使用 self 操作符。如果你想在另一个类上使用常量,你可以使用反射
class Foo {
const ERR_SOME_CONST = 6001;
function bar() {
self::ERR_SOME_CONST;
}
}

