1

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?

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.