Reputation: 10048
I need to print the constant name instead of the number:
class Type
{
const UNKNOWN = 0;
const PERSON = 1;
}
I have a function: entity->getType()
Which return a number in this case 0 or 1.
How can I use PHP to convert the const UNKNOWN or PERSON to text without doing this:
$entity_types = [
0 => 'UNKNOWN',
1 => 'PERSON'];
printf('Type: %s' . PHP_EOL, $entity_types[$entity->getType()]);
But by calling:
Type::$entity->getType()
?
Upvotes: 0
Views: 83
Reputation: 15629
Actually, there's no real solution to your problem. Simple example, why this couldn't work in PHP:
const VAR1 = 1;
const VAR2 = 1;
That is a total valid usage of class constants, but as there are multiple uses of the value 1
, there isn't a mapping of 1
to any name.
There might be a way to use the reflection api to return the first constant with a matching value, but doing this in production isn't recommend, as this isn't very fast (and as I said before, also unsafe if you later change your code)
If you want to improve the readability if const values, you should think about using string's as values for the constants and not numbers.
Upvotes: 2