Re: Re: Clarification on the Enum language structure

From: Date: Wed, 23 Feb 2011 23:10:41 +0000
Subject: Re: Re: Clarification on the Enum language structure
References: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  Groups: php.internals 
Request: Send a blank email to internals+get-51525@lists.php.net to get a copy of this message
On 24/02/11 8:33 AM, Stas Malyshev wrote:
Hi!
use the function: you would usually be expected to pass in a true enum constant of the MyEnum type.
That works wonders in dynamic languages, without any means of really ensuring it.
No, I believe you can ensure it, and you can even ensure it efficiently.
I don't see how you can do it without typing variables and functions and doing static type control.
You can do it like this. When an enum is defined: - internally create a class to represent the enum; flag it as an enum class, not a regular class; this restricts any PHP code from attempting to access properties of the class, instantiate it, etc.. - internally instantiate an object of the class for every enum constant; each object contains a member with the integer/string representation of the constant. - internally create a static array in the class, associating every enum value to its instantiated object. When an enum is type-hinted, you just check the value is internally an object of the enum class. When cast to integer or string, or serialising, or used in a context where an integer or string is required, simply use the scalar value in the enum object. Perhaps do this whenever passed to a built-in function, too, unless explicitly type-hinted, or a special case such as call_user_func where the enum is going to work its way back into PHP code, merely as a convenience to avoid needing to change a lot of C code to check and cast enums. When cast to enum, or deserialising, look up the relevant integer or string in the internal enum class's array to efficiently get the strongly typed enum value. When comparing enums for equality, compare pointers only. There will always be exactly one internal object for each enum constant, so this will work. When comparing enums for ordering (less than, greater than), look up the scalar values and compare them.
Even then - what if you read values from config file or database? Would you have 50-item switch to match config values to typed Enum values?
You'd just cast it to the enum type, at which point PHP would look up the enum value in the internal array in the enum class to efficiently retrieve the relevant strongly typed enum constant. I also suggest when type-hinting, if the type is integer or string where an enum is expected, PHP attempts a cast before failing, to make this more convenient. Ben.

« previous php.internals (#51525) next »