Reputation: 68492
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"
}
}
Can I get it without a huge case statement?
Upvotes: 1
Views: 199
Reputation: 17415
PHP:
========================================
C#
Your answer is here by Jon Skeet
Determine the name of a constant based on the value
Or use enume (converting enume name to string is easy:)
public enum Ram{a,b,c}
Ram MyEnume = Ram.a;
MyEnume.ToString()
Upvotes: 1
Reputation: 2635
Have a look at ReflectionClass::getConstants.
Something like (it's pretty ugly and inefficient, btw):
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;
}
}
Upvotes: 3
Reputation: 5108
You can use the [Reflection][1]
for this.
Assuming you have the below class.
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());
Upvotes: 2