Skip to content

Core\Reflect\EnumInfo::name

$enumInfo->name(): string

Returns the full name of the enum that a Core\Reflect\EnumInfo describes.

You get a description with Core\Reflect\EnumInfo::of, and you pass it the name of an enum. name() returns that same name as a string, with its namespace. This is useful in a function that gets only the description, for example to print a heading or a log line. You can also store the name and pass it to of again later. The result is a description of the same enum.

The examples below print the name, use it to describe the enum again, and write a heading for each enum in the documentation of an API.

Return value

Returns string. The name that was passed to of, with its namespace. You can pass it to of again to get a description of the same enum.

Examples

Print the name

<?nvs
// Shows how to read the name of the enum that a description is about.
enum Priority: uint
{
Low = 1,
High = 2,
}
?Core\Reflect\EnumInfo $found = Core\Reflect\EnumInfo::of(Priority::class);
if ($found != null) {
Core\Reflect\EnumInfo $info = $found;
// `name()` returns the name that was passed to `of`. This prints `Priority`.
echo $info->name(), "\n";
}
Output
Priority

Describe the same enum again

<?nvs
// Shows that the name from `name()` can be passed to `of` to describe the same enum again.
enum Channel: int
{
Email = 1,
Sms = 2,
}
?Core\Reflect\EnumInfo $first = Core\Reflect\EnumInfo::of(Channel::class);
if ($first != null) {
Core\Reflect\EnumInfo $info = $first;
// Only the name is stored, as a string. Later, `of` gives a new description from it.
string $saved = $info->name();
?Core\Reflect\EnumInfo $second = Core\Reflect\EnumInfo::of($saved);
if ($second != null) {
Core\Reflect\EnumInfo $again = $second;
// This prints `Channel: Email, Sms`.
echo $again->name(), ': ', Core\Str::join($again->cases(), ', '), "\n";
}
}
Output
Channel: Email, Sms

A heading for each enum in the api docs

<?nvs
// Writes one heading and one table row per case for each enum an API returns.
enum OrderState: int
{
Open = 1,
Paid = 2,
}
enum Currency: uint
{
Eur = 978,
Usd = 840,
}
class ApiDocs
{
// The function gets only the description. `name()` gives the heading.
public static function section(Core\Reflect\EnumInfo $info): string
{
string $text = '## ' . $info->name() . "\n";
foreach ($info->cases() as string $case) {
$text = $text . '| ' . $case . " |\n";
}
return $text;
}
}
array<string> $names = [OrderState::class, Currency::class];
foreach ($names as string $name) {
?Core\Reflect\EnumInfo $found = Core\Reflect\EnumInfo::of($name);
if ($found != null) {
Core\Reflect\EnumInfo $info = $found;
echo ApiDocs::section($info);
}
}
Output
## OrderState
| Open |
| Paid |
## Currency
| Usd |
| Eur |