Last active
May 17, 2023 18:55
-
-
Save thallisphp/e71c9e6b66b56023df1ace0f158905b6 to your computer and use it in GitHub Desktop.
PHP - Enum com descrição por atributo - Enum with description by attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#[Attribute(Attribute::TARGET_CLASS_CONSTANT)] | |
readonly class Descricao | |
{ | |
public function __construct( | |
public string $descricao, | |
) | |
{ | |
} | |
} | |
enum TipoPessoa: string | |
{ | |
#[Descricao('Pessoa Física')] | |
case Fisica = 'PF'; | |
#[Descricao('Pessoa Jurídica')] | |
case Juridica = 'PJ'; | |
public function descricao(): string | |
{ | |
return (new ReflectionEnumBackedCase(static::class, $this->name)) | |
->getAttributes(Descricao::class)[0] | |
->newInstance() | |
->descricao; | |
} | |
} | |
print_r([ | |
TipoPessoa::Fisica->value, // PF | |
TipoPessoa::Juridica->value, // PJ | |
TipoPessoa::Fisica->descricao(), // Pessoa Física | |
TipoPessoa::Juridica->descricao(), // Pessoa Jurídica | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment