const
STUFF = 1,
MORE_STUFF = 3,
...
LAST_STUFF = 45;
function($id = self::STUFF){
if(defined('self::'.$id)){
// here how do I get the name of the constant?
// eg "STUFF"
}
}
我可以在没有大量案例陈述的情况下得到它吗?
答案 0 :(得分:3)
查看ReflectionClass::getConstants。
类似的东西(它非常丑陋且低效,顺便说一下):
class Foo {
const
STUFF = 1,
MORE_STUFF = 3,
...
LAST_STUFF = 45;
function get_name($id = self::STUFF)
{
$rc = new ReflectionClass ('Foo');
$consts = $oClass->getConstants ();
foreach ($consts as $name => $value) {
if ($value === $id) {
return $name;
}
}
return NULL;
}
}
答案 1 :(得分:2)
您可以使用[Reflection][1]
。
假设你有以下课程。
class Profile {
const LABEL_FIRST_NAME = "First Name";
const LABEL_LAST_NAME = "Last Name";
const LABEL_COMPANY_NAME = "Company";
}
$refl = new ReflectionClass('Profile');
print_r($refl->getConstants());
答案 2 :(得分:1)
PHP:
========================================
C#
你的答案来自 Jon Skeet
Determine the name of a constant based on the value
或者使用enume(将enume name转换为string很简单:)
public enum Ram{a,b,c}
Ram MyEnume = Ram.a;
MyEnume.ToString()