假设你在一个类中定义的常数:如何获取常量的名称?
class Foo {
const ERR_SOME_CONST = 6001;
function bar() {
$x = 6001;
// need to get 'ERR_SOME_CONST'
}
}
是否有可能用PHP?
假设你在一个类中定义的常数:如何获取常量的名称?
class Foo {
const ERR_SOME_CONST = 6001;
function bar() {
$x = 6001;
// need to get 'ERR_SOME_CONST'
}
}
是否有可能用PHP?
您可以用reflection API
我假设你想获得基于您的变量(常数变量==值的值)的值的常量的名称得到他们。获取在类中定义的所有常量,遍历它们并将这些常量的值与变量的值进行比较。 请注意,如果存在两个具有相同值的常量,则可以使用此方法获得其他常数。
例如:
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:你介意告诉你为什么需要这个,因为它看起来非常不寻常的...
与反思:
$class = new ReflectionClass("Foo");
$constants = $class->getConstants();
$constants
是一个数组它包含Foo类中定义的常量的所有名称和值。
使用此函数可以将所有常量分配给一个数组。
$const = get_defined_constants();
然后使用下面的函数可以打印阵列结构
echo "<pre>";
print_r($const);
,你可以看到更多的解释在这里www.sugunan.com
这里是我做了什么来实现它。启发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];
}
}
只是想说如果常数具有相同的值,这将不起作用。大部分时间不应该成为问题,但是... – Populus 2014-06-24 20:20:06
我知道这是一个老问题,所有的,但我还是觉得我有一些有用的投入。我使用一个抽象类来实现它,所有的枚举都可以扩展。抽象类包含一个通用的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;
}
这样你就可以得到一个人类可读的字符串输出使用,每个扩展底座枚举枚举。此外,您的枚举实现(final
)无法扩展,因为BaseEnum
中的构造函数是private
,因此永远不能实例化。
因此,举例来说,如果你表现出他们的类型的所有用户名的列表,你可以这样做
foreach($users as $user){
echo "<li>{$user->name}, ".UserType::toString($user->usertype)."</li>";
}
,如果你需要得到在同一类的方法的恒定值,你只需要使用自我操作员。你可以使用反射,如果你想使用另一个类上的常量
class Foo {
const ERR_SOME_CONST = 6001;
function bar() {
self::ERR_SOME_CONST;
}
}
警告:这种方式,你不应该编程...(如果你不确定youre做什么:))
我写了1排由你选择的CATEGORY_
所以这里回声常数和它们的数值是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;
列表如果你只想要一个您所渴望的由数=>我创建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.";}
因此,例如索姆Ë信息以数字64常数:
echo "NameOfConstant: ".getConstantName("INFO_",64);
将输出类似:NameOfConstant: INFO_LICENSE
所有其他的答案涵盖的要点。但是,如果疯狂的一个衬垫是你的事,那么:
function getConstantName($class, $value)
{
return array_flip((new \ReflectionClass($class))->getConstants())[$value];
}
如果你需要处理其中的值可能不是实际上是常量之一的话,那么你可以放弃一个额外的行:
function getConstantName($class, $value)
{
$map = array_flip((new \ReflectionClass($class))->getConstants());
return (array_key_exists($value, $map) ? $map[$value] : null);
}
这是简单快捷的解决方案。翻转阵列并检查密钥。 – 2016-04-12 08:15:13
好吧,好吧,我知道一切已经涵盖:) 但JanHančič要求用例,所以我会分享我的。另外:大家似乎都使用array_flip()。为什么不是array_search()?
我需要它在一个扩展了\ Exception的类中,并且是我的一些小的具体异常的基类。每个具体的异常类都涵盖了一个广泛的异常域,并定义了几个精确的异常原因。原因?我不想有一大堆例外来维护和记住。此外,还有一个异常处理程序集,它将异常的内容转储到日志文件中 - 在这里我需要获取常量名称,试图从相当痛苦的状态中解析异常原因。从我的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());
});
没什么大不了,其实。只是想从类函数传递错误代码的方式。至于我const ERR_SOME_ERROR ='ERR_SOME_ERROR'看起来很奇怪,我认为我的getLastError()函数可能会返回类似数组(5003 =>'ERR_SOME_ERROR',5002 =>'ERR_SOME_ERR2')等等。 只是要返回错误代码和错误名称。那么,我越想到它,我可能不会使用它(因为你说的不寻常的语法):) – 2009-12-10 11:09:47
也需要它的CURLE_ *常量支持,其中'curl_multi_strerror'不可用 – 2013-10-03 08:36:16
我“需要”的东西像这样,以便提供更好的错误输出,而不必重写如何跟踪存储为常量的某些错误代码。 – Frug 2015-04-21 14:30:11