Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerations on PHP

I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.

Constants do the trick, but there's the namespace collision problem and (or actually because) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.

Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?

like image 691
Henrik Paul Avatar asked Oct 31 '08 18:10

Henrik Paul


People also ask

Are there enums in PHP?

In PHP, Enums are a special kind of object. The Enum itself is a class, and its possible cases are all single-instance objects of that class. That means Enum cases are valid objects and may be used anywhere an object may be used, including type checks.

When were enums added PHP?

From PHP 8.1, you can use native enumerations.

What are enumerations explain with example?

An enumeration is used in any programming language to define a constant set of values. For example, the days of the week can be defined as an enumeration and used anywhere in the program. In C#, the enumeration is defined with the help of the keyword 'enum'.

What are enumerations in code?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.


2 Answers

There is a native extension, too. The SplEnum

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

http://www.php.net/manual/en/class.splenum.php

Attention:

https://www.php.net/manual/en/spl-types.installation.php

The PECL extension is not bundled with PHP.

A DLL for this PECL extension is currently unavailable.

like image 29
9 revs, 8 users 29% Avatar answered Nov 26 '22 13:11

9 revs, 8 users 29%


Depending upon use case, I would normally use something simple like the following:

abstract class DaysOfWeek {     const Sunday = 0;     const Monday = 1;     // etc. }  $today = DaysOfWeek::Sunday; 

However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:

abstract class BasicEnum {     private static $constCacheArray = NULL;      private static function getConstants() {         if (self::$constCacheArray == NULL) {             self::$constCacheArray = [];         }         $calledClass = get_called_class();         if (!array_key_exists($calledClass, self::$constCacheArray)) {             $reflect = new ReflectionClass($calledClass);             self::$constCacheArray[$calledClass] = $reflect->getConstants();         }         return self::$constCacheArray[$calledClass];     }      public static function isValidName($name, $strict = false) {         $constants = self::getConstants();          if ($strict) {             return array_key_exists($name, $constants);         }          $keys = array_map('strtolower', array_keys($constants));         return in_array(strtolower($name), $keys);     }      public static function isValidValue($value, $strict = true) {         $values = array_values(self::getConstants());         return in_array($value, $values, $strict);     } } 

By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:

abstract class DaysOfWeek extends BasicEnum {     const Sunday = 0;     const Monday = 1;     const Tuesday = 2;     const Wednesday = 3;     const Thursday = 4;     const Friday = 5;     const Saturday = 6; }  DaysOfWeek::isValidName('Humpday');                  // false DaysOfWeek::isValidName('Monday');                   // true DaysOfWeek::isValidName('monday');                   // true DaysOfWeek::isValidName('monday', $strict = true);   // false DaysOfWeek::isValidName(0);                          // false  DaysOfWeek::isValidValue(0);                         // true DaysOfWeek::isValidValue(5);                         // true DaysOfWeek::isValidValue(7);                         // false DaysOfWeek::isValidValue('Friday');                  // false 

As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).

Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.

like image 115
Brian Cline Avatar answered Nov 26 '22 13:11

Brian Cline