Q: Is there a way to dynamically create class constants?
Answer: Yes, but do not do this :)
class EnumFactory { public static function create($class, array $constants) { $declaration = ''; foreach($constants as $name => $value) { $declaration .= 'const ' . $name . ' = ' . $value . ';'; } eval("class $class { $declaration }"); } } EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2)); echo darkSide::FOO . ' ' . darkSide::BAR;
The next question ...
Q: Signatures of a constraint function. I want to be able to request a "set" of values ββas input to a function. For example: public function do_something ( ENUM_Types $type ) {}
According to manual , in this case $type must be an instance of the ENUM_Types class. But for a constant it is impossible (they cannot contain objects).
But wait ... We can use this trick:
class Enum { protected static $_constantToClassMap = array(); protected static function who() { return __CLASS__; } public static function registerConstants($constants) { $class = static::who(); foreach ($constants as $name => $value) { self::$_constantToClassMap[$class . '_' . $name] = new $class(); } } public static function __callStatic($name, $arguments) { return self::$_constantToClassMap[static::who() . '_' . $name]; } } class EnumFactory { public static function create($class, $constants) { $declaration = ''; foreach($constants as $name => $value) { $declaration .= 'const ' . $name . ' = ' . $value . ';'; } eval("class $class extends Enum { $declaration protected static function who() { return __CLASS__; } }"); $class::registerConstants($constants); } } EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2)); EnumFactory::create('aaa', array('FOO' => 1, 'BAR' => 2)); echo (aaa::BAR() instanceof aaa) ? 'Yes' : 'No';
And after that we can use the "hint type":
function doSomething(darkSide $var) { echo 'Bu!'; } doSomething(darkSide::BAR()); doSomething(aaa::BAR());
Q: Simple and compact. Allow simple and compact syntax when used in code. For example, using constants, I can write a conditional statement, for example: if ( $my_var === ENUM_Types::TypeA ) {}
You can use the values ββof your pseudo-constants in this form:
if (darkSide::FOO === 1) {}
Q: Dynamic enumeration. I would like this enumeration to be managed through an interface and stored in a database (I use the Wordpress admin screens for this if someone cares). During the execution of this βlistβ, it should be pulled out of the database and made available for the code as an enumeration (or a similar structure that achieves the goals above).
You can initialize the enumeration by passing an array to EnumFactory::create($class, $constants) :
EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2));