Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top