Create enumerations in PHP
This article demonstrates how to create enumeration objects in PHP.
Enumerations are a convenient way to define a set of named values representing integral constants. PHP doesn’t support enumerations. However, you can emulate enumeration by using any of the following methods:
1. Using abstract class
The first option to emulate enumeration is using the class constants. You can create an abstract class containing the constants, and then access the constant values by using the ClassName::ConstantName syntax. Here’s an example of how you could achieve that.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php abstract class HTTPResponseStatusCodes { const OK = 200; const CREATED = 201; const ACCEPTED = 202; const BAD_REQUEST = 400; const UNAUTHORIZED = 401; const FORBIDDEN = 403; } $success = HTTPResponseStatusCodes::OK; echo $success; // 200 ?> |
2. Using array
Another option to emulate enumerations in PHP is to create an associative array of constant names and their integer constants. In PHP, this translates to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $enum = array( "OK" => 200, "CREATED" => 201, "ACCEPTED" => 202, "BAD_REQUEST" => 400, "UNAUTHORIZED" => 401, "FORBIDDEN" => 403 ); $success = $enum["OK"]; echo $success; // 200 ?> |
Alternatively, you can create an associative array of constant names and values within a class. Then you can create a static helper function to return the constant value using its name, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php class HTTPResponseStatusCodes { private static $enum = array( "OK" => 200, "CREATED" => 201, "ACCEPTED" => 202, "BAD_REQUEST" => 400, "UNAUTHORIZED" => 401, "FORBIDDEN" => 403 ); public static function EnumValue($ordinal) { return self::$enum[$ordinal]; } } $success = HTTPResponseStatusCodes::EnumValue("OK"); echo $success; // 200 ?> |
3. Using define() function
Finally, you can emulate enumeration constants by defining a named constant using the define() function. The following example provides an illustration.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php define("OK", 200); define("CREATED", 201); define("ACCEPTED", 202); define("BAD_REQUEST", 400); define("UNAUTHORIZED", 401); define("FORBIDDEN", 403); $success = OK; echo $success; // 200 ?> |
That’s all about creating enumeration objects in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)