Enumerations in PHP


What is PHP?

PHP (Hypertext Preprocessor) is a popular scripting language designed for web development. It is widely used for creating dynamic and interactive web pages. PHP code can be embedded directly into HTML, allowing developers to mix PHP and HTML seamlessly. PHP can connect to databases, process form data, generate dynamic content, handle file uploads, interact with servers, and perform various server-side tasks. It supports a wide range of web development frameworks, such as Laravel, Symfony, and CodeIgniter, which provide additional tools and features for building web applications. PHP is an open-source language with a large community, extensive documentation, and a rich ecosystem of libraries and extensions.

What are Enumerations?

Enumerations are a data type commonly found in programming languages that allow you to define a set of named values. Enumerations provide a way to represent a fixed set of constants that are typically used as options or choices in your code. They make your code more readable, self-explanatory, and help prevent errors by restricting the possible values that a variable can take.

While PHP does not have native enums, you can simulate enums using different approaches, such as using class constants or abstract classes, these approaches can provide some level of encapsulation and organization for your constant values, but they do not offer the full functionality and type safety of native enums in other languages.

Using abstract class

Example

<?php
// PHP program to demonstrate the use of encapsulated constants
// Encapsulating constants
abstract class MyEnum {
   const VALUE1 = "Haveesh";
   const VALUE2 = 1;
   const VALUE3 = ['a' => 1, 'b' => 2];
}

$a = MyEnum::VALUE1;
$b = MyEnum::VALUE2;
$c = MyEnum::VALUE3;
var_dump($a);
var_dump($b);
var_dump($c);
?>

Output

string(7) "Haveesh"
int(1)
array(2) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
}

By Extending an Abstract Class

Example

<?php
// PHP program to show use of enumerations

// Base enumeration class
abstract class Enum {

   // Enumeration constructor
   final public function __construct($value) {
      $this->value = $value;
   }

   // String representation
   final public function __toString() {
      return $this->value;
   }
}

// Encapsulating enumerated constants
class test extends Enum {
   const dummy_string = "Hasvitha";
   const dummy_int   = 1;
   const dummy_array  = array('a' => 1, 'b' => 2);
}

$a = new test(test::dummy_string);
$b = new test(test::dummy_int);
$c = new test(test::dummy_array);

var_dump($a);
var_dump($b);
var_dump($c);

?>

Output

object(test)#1 (1) {
  ["value"]=>
  string(8) "Hasvitha"
}
object(test)#2 (1) {
  ["value"]=>
  int(1)
}
object(test)#3 (1) {
  ["value"]=>
  array(2) {
    ["a"]=>
    int(1)
    ["b"]=>
    int(2)
  }
}

Adding Exception Handling

Example

<?php
// PHP program to show use of enumerations
  
// Base enumeration class
abstract class Enum {
  
   // Enumeration constructor
   final public function __construct($value) {
      try {
         $c = new ReflectionClass($this);
  
         // Content validation
         if(!in_array($value, $c->getConstants())) {
            try {
               throw new 
               Exception("IllegalArgumentException");
            }
            catch (Exception $S) {
               echo $S->getMessage();
            }
         }
         $this->value = $value;
      }
      catch (Exception $S){
         echo $S->getMessage();
      }
   }
  
   // String representation
   final public function __toString() {
      return $this->value;
   }
}
  
// Encapsulating enumerated constants
class example extends Enum {
   const dummy_string = "John Martin";
   const dummy_int   = 1;
   const dummy_array  = array('a' => 1, 'b' => 2);
}
  
$a = new example(example::dummy_string);
$b = new example(example::dummy_int);
$c = new example(example::dummy_array);
$d = new example(1.414);
  
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Output

IllegalArgumentExceptionobject(example)#1 (1) {
  ["value"]=>
  string(11) "John Martin"
}
object(example)#2 (1) {
  ["value"]=>
  int(1)
}
object(example)#3 (1) {
  ["value"]=>
  array(2) {
    ["a"]=>
    int(1)
    ["b"]=>
    int(2)
  }
}
object(example)#4 (1) {
  ["value"]=>
  float(1.414)
}

Conclusion

Enums are a valuable tool for representing a fixed set of named constants, enhancing code readability and maintainability. While PHP lacks native enum support, alternative approaches can be used to simulate enums, such as using class constants or abstract classes. These approaches provide encapsulation and organization for constant values. However, they do not offer the full functionality and type safety of native enums found in other programming languages. Despite this limitation, leveraging enums in PHP, whether through workarounds or future native support, can improve code clarity, reduce errors, and facilitate the expression of intent in the use of constant values.

Updated on: 28-Jul-2023

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements