Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class DaysOfWeek
- {
- const Sunday = 0;
- const Monday = 1;
- // etc.
- }
- var $today = DaysOfWeek::Sunday;
- <?php
- class YourClass
- {
- const SOME_CONSTANT = 1;
- public function echoConstant()
- {
- echo self::SOME_CONSTANT;
- }
- }
- echo YourClass::SOME_CONSTANT;
- $c = new YourClass;
- $c->echoConstant();
- class SomeTypeName {
- private static $enum = array(1 => "Read", 2 => "Write");
- public function toOrdinal($name) {
- return array_search($name, self::$enum);
- }
- public function toString($ordinal) {
- return self::$enum[$ordinal];
- }
- }
- class Enum {
- const NAME = 'aaaa';
- const SOME_VALUE = 'bbbb';
- }
- print Enum::NAME;
- <?php
- /**
- * Class Enum
- *
- * @author Christopher Fox <[email protected]>
- *
- * @version 1.0
- *
- * This class provides the function of an enumeration.
- * The values of Enum elements are unique (even between different Enums)
- * as you would expect them to be.
- *
- * Constructing a new Enum:
- * ========================
- *
- * In the following example we construct an enum called "UserState"
- * with the elements "inactive", "active", "banned" and "deleted".
- *
- * <code>
- * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');
- * </code>
- *
- * Using Enums:
- * ============
- *
- * The following example demonstrates how to compare two Enum elements
- *
- * <code>
- * var_dump(UserState::inactive == UserState::banned); // result: false
- * var_dump(UserState::active == UserState::active); // result: true
- * </code>
- *
- * Special Enum methods:
- * =====================
- *
- * Get the number of elements in an Enum:
- *
- * <code>
- * echo UserState::CountEntries(); // result: 4
- * </code>
- *
- * Get a list with all elements of the Enum:
- *
- * <code>
- * $allUserStates = UserState::GetEntries();
- * </code>
- *
- * Get a name of an element:
- *
- * <code>
- * echo UserState::GetName(UserState::deleted); // result: deleted
- * </code>
- *
- * Get an integer ID for an element (e.g. to store as a value in a database table):
- * This is simply the index of the element (beginning with 1).
- * Note that this ID is only unique for this Enum but now between different Enums.
- *
- * <code>
- * echo UserState::GetDatabaseID(UserState::active); // result: 2
- * </code>
- */
- class Enum
- {
- /**
- * @var Enum $instance The only instance of Enum (Singleton)
- */
- private static $instance;
- /**
- * @var array $enums An array of all enums with Enum names as keys
- * and arrays of element names as values
- */
- private $enums;
- /**
- * Constructs (the only) Enum instance
- */
- private function __construct()
- {
- $this->enums = array();
- }
- /**
- * Constructs a new enum
- *
- * @param string $name The class name for the enum
- * @param mixed $_ A list of strings to use as names for enum entries
- */
- public static function Create($name, $_)
- {
- // Create (the only) Enum instance if this hasn't happened yet
- if (self::$instance===null)
- {
- self::$instance = new Enum();
- }
- // Fetch the arguments of the function
- $args = func_get_args();
- // Exclude the "name" argument from the array of function arguments,
- // so only the enum element names remain in the array
- array_shift($args);
- self::$instance->add($name, $args);
- }
- /**
- * Creates an enumeration if this hasn't happened yet
- *
- * @param string $name The class name for the enum
- * @param array $fields The names of the enum elements
- */
- private function add($name, $fields)
- {
- if (!array_key_exists($name, $this->enums))
- {
- $this->enums[$name] = array();
- // Generate the code of the class for this enumeration
- $classDeclaration = "class " . $name . " {n"
- . "private static $name = '" . $name . "';n"
- . $this->getClassConstants($name, $fields)
- . $this->getFunctionGetEntries($name)
- . $this->getFunctionCountEntries($name)
- . $this->getFunctionGetDatabaseID()
- . $this->getFunctionGetName()
- . "}";
- // Create the class for this enumeration
- eval($classDeclaration);
- }
- }
- /**
- * Returns the code of the class constants
- * for an enumeration. These are the representations
- * of the elements.
- *
- * @param string $name The class name for the enum
- * @param array $fields The names of the enum elements
- *
- * @return string The code of the class constants
- */
- private function getClassConstants($name, $fields)
- {
- $constants = '';
- foreach ($fields as $field)
- {
- // Create a unique ID for the Enum element
- // This ID is unique because class and variables
- // names can't contain a semicolon. Therefore we
- // can use the semicolon as a separator here.
- $uniqueID = $name . ";" . $field;
- $constants .= "const " . $field . " = '". $uniqueID . "';n";
- // Store the unique ID
- array_push($this->enums[$name], $uniqueID);
- }
- return $constants;
- }
- /**
- * Returns the code of the function "GetEntries()"
- * for an enumeration
- *
- * @param string $name The class name for the enum
- *
- * @return string The code of the function "GetEntries()"
- */
- private function getFunctionGetEntries($name)
- {
- $entryList = '';
- // Put the unique element IDs in single quotes and
- // separate them with commas
- foreach ($this->enums[$name] as $key => $entry)
- {
- if ($key > 0) $entryList .= ',';
- $entryList .= "'" . $entry . "'";
- }
- return "public static function GetEntries() { n"
- . " return array(" . $entryList . ");n"
- . "}n";
- }
- /**
- * Returns the code of the function "CountEntries()"
- * for an enumeration
- *
- * @param string $name The class name for the enum
- *
- * @return string The code of the function "CountEntries()"
- */
- private function getFunctionCountEntries($name)
- {
- // This function will simply return a constant number (e.g. return 5;)
- return "public static function CountEntries() { n"
- . " return " . count($this->enums[$name]) . ";n"
- . "}n";
- }
- /**
- * Returns the code of the function "GetDatabaseID()"
- * for an enumeration
- *
- * @return string The code of the function "GetDatabaseID()"
- */
- private function getFunctionGetDatabaseID()
- {
- // Check for the index of this element inside of the array
- // of elements and add +1
- return "public static function GetDatabaseID($entry) { n"
- . "$key = array_search($entry, self::GetEntries());n"
- . " return $key + 1;n"
- . "}n";
- }
- /**
- * Returns the code of the function "GetName()"
- * for an enumeration
- *
- * @return string The code of the function "GetName()"
- */
- private function getFunctionGetName()
- {
- // Remove the class name from the unique ID
- // and return this value (which is the element name)
- return "public static function GetName($entry) { n"
- . "return substr($entry, strlen(self::$name) + 1 , strlen($entry));n"
- . "}n";
- }
- }
- ?>
- $value = "concert";
- $Enumvalue = EnumCategory::enum($value);
- //$EnumValue = 1
- class EnumCategory{
- const concert = 1;
- const festival = 2;
- const sport = 3;
- const nightlife = 4;
- const theatre = 5;
- const musical = 6;
- const cinema = 7;
- const charity = 8;
- const museum = 9;
- const other = 10;
- public function enum($string){
- return constant('EnumCategory::'.$string);
- }
- }
- class EnumCategory {
- static $concert = 1;
- static $festival = 2;
- static $sport = 3;
- static $nightlife = 4;
- static $theatre = 5;
- static $musical = 6;
- static $cinema = 7;
- static $charity = 8;
- static $museum = 9;
- static $other = 10;
- }
- EnumCategory::${$category};
- <?php
- //require the library
- require_once __DIR__ . '/src/Enum.func.php';
- //if you don't have a cache directory, create one
- @mkdir(__DIR__ . '/cache');
- EnumGenerator::setDefaultCachedClassesDir(__DIR__ . '/cache');
- //Class definition is evaluated on the fly:
- Enum('FruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'));
- //Class definition is cached in the cache directory for later usage:
- Enum('CachedFruitsEnum', array('apple' , 'orange' , 'rasberry' , 'bannana'), 'mycompanynamespace', true);
- echo 'FruitsEnum::APPLE() == FruitsEnum::APPLE(): ';
- var_dump(FruitsEnum::APPLE() == FruitsEnum::APPLE()) . "n";
- echo 'FruitsEnum::APPLE() == FruitsEnum::ORANGE(): ';
- var_dump(FruitsEnum::APPLE() == FruitsEnum::ORANGE()) . "n";
- echo 'FruitsEnum::APPLE() instanceof Enum: ';
- var_dump(FruitsEnum::APPLE() instanceof Enum) . "n";
- echo 'FruitsEnum::APPLE() instanceof FruitsEnum: ';
- var_dump(FruitsEnum::APPLE() instanceof FruitsEnum) . "n";
- echo "->getName()n";
- foreach (FruitsEnum::iterator() as $enum)
- {
- echo " " . $enum->getName() . "n";
- }
- echo "->getValue()n";
- foreach (FruitsEnum::iterator() as $enum)
- {
- echo " " . $enum->getValue() . "n";
- }
- echo "->getOrdinal()n";
- foreach (CachedFruitsEnum::iterator() as $enum)
- {
- echo " " . $enum->getOrdinal() . "n";
- }
- echo "->getBinary()n";
- foreach (CachedFruitsEnum::iterator() as $enum)
- {
- echo " " . $enum->getBinary() . "n";
- }
- FruitsEnum::APPLE() == FruitsEnum::APPLE(): bool(true)
- FruitsEnum::APPLE() == FruitsEnum::ORANGE(): bool(false)
- FruitsEnum::APPLE() instanceof Enum: bool(true)
- FruitsEnum::APPLE() instanceof FruitsEnum: bool(true)
- ->getName()
- APPLE
- ORANGE
- RASBERRY
- BANNANA
- ->getValue()
- apple
- orange
- rasberry
- bannana
- ->getValue() when values have been specified
- pig
- dog
- cat
- bird
- ->getOrdinal()
- 1
- 2
- 3
- 4
- ->getBinary()
- 1
- 2
- 4
- 8
- class FruitsEnum {
- static $APPLE = null;
- static $ORANGE = null;
- private $value = null;
- public static $map;
- public function __construct($value) {
- $this->value = $value;
- }
- public static function init () {
- self::$APPLE = new FruitsEnum("Apple");
- self::$ORANGE = new FruitsEnum("Orange");
- //static map to get object by name - example Enum::get("INIT") - returns Enum::$INIT object;
- self::$map = array (
- "Apple" => self::$APPLE,
- "Orange" => self::$ORANGE
- );
- }
- public static function get($element) {
- if($element == null)
- return null;
- return self::$map[$element];
- }
- public function getValue() {
- return $this->value;
- }
- public function equals(FruitsEnum $element) {
- return $element->getValue() == $this->getValue();
- }
- public function __toString () {
- return $this->value;
- }
- }
- FruitsEnum::init();
- var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$APPLE)); //true
- var_dump(FruitsEnum::$APPLE->equals(FruitsEnum::$ORANGE)); //false
- var_dump(FruitsEnum::$APPLE instanceof FruitsEnum); //true
- var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::$APPLE)); //true - enum from string
- var_dump(FruitsEnum::get("Apple")->equals(FruitsEnum::get("Orange"))); //false
Add Comment
Please, Sign In to add comment