PHP Class Constants Array Cast
-
25-05-2021 - |
Pergunta
To simulate enums in PHP I like to use class constants.
e.g.
class FRUIT
{
const apple = 1;
const orange = 2;
const lemon = 3;
const pear = 4;
};
I have a case where I'd like cast this class to an array to populate a select list. However because class constants behave statically casting does not work e.g. (array)(new FRUIT());
nor does the get_object_vars()
method.
What's the best way to get round this? Do I need to create an internal function to iterate the constants and return an array?
Solução
Do I need to create an internal function to iterate the constants and return an array?
Nope! You can use Reflection to do that:
$r = new ReflectionClass('FRUIT');
$constants = $r->getConstants();
More info here
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow