Enumeration (or enum) is mainly used to assign names to integral constants, the names make a program easy to read and maintain. In PHP, enumeration datatypes can be implemented using and extending abstract classes.
Approach 1: Using simple abstract class to for data member encapsulation.
Example:
<?php
abstract class gfg {
const dummy_string = "geeksforgeeks" ;
const dummy_int = 1;
const dummy_array = array ( 'a' => 1, 'b' => 2);
}
$a = gfg::dummy_string;
$b = gfg::dummy_int;
$c = gfg::dummy_array;
var_dump( $a );
var_dump( $b );
var_dump( $c );
?>
|
Output:
string(13) "geeksforgeeks"
int(1)
array(2) {
["a"]=>
int(1)
["b"]=>
int(2)
}
Approach 2: Extend an abstract class acting as an enumeration container for encapsulating constants.
Example:
<?php
abstract class enum {
final public function __construct( $value ) {
$this ->value = $value ;
}
final public function __toString() {
return $this ->value;
}
}
class gfg extends enum {
const dummy_string = "geeksforgeeks" ;
const dummy_int = 1;
const dummy_array = array ( 'a' => 1, 'b' => 2);
}
$a = new gfg(gfg::dummy_string);
$b = new gfg(gfg::dummy_int);
$c = new gfg(gfg::dummy_array);
var_dump( $a );
var_dump( $b );
var_dump( $c );
?>
|
Output:
object(gfg)#1 (1) {
["value"]=>
string(13) "geeksforgeeks"
}
object(gfg)#2 (1) {
["value"]=>
int(1)
}
object(gfg)#3 (1) {
["value"]=>
array(2) {
["a"]=>
int(1)
["b"]=>
int(2)
}
}
Approach 3: Enumeration mentioned in the previous approach can be specialized by addition of validity checks and exception handling for more flexible usage of enumeration datatype.
Example:
<?php
abstract class enum {
final public function __construct( $value ) {
try {
$c = new ReflectionClass( $this );
if (!in_array( $value , $c ->getConstants())) {
try {
throw new
Exception( "IllegalArgumentException" );
}
catch (Exception $k ) {
echo $k ->getMessage();
}
}
$this ->value = $value ;
}
catch (Exception $k ){
echo $k ->getMessage();
}
}
final public function __toString() {
return $this ->value;
}
}
class gfg extends enum {
const dummy_string = "geeksforgeeks" ;
const dummy_int = 1;
const dummy_array = array ( 'a' => 1, 'b' => 2);
}
$a = new gfg(gfg::dummy_string);
$b = new gfg(gfg::dummy_int);
$c = new gfg(gfg::dummy_array);
$d = new gfg(3.14);
var_dump( $a );
var_dump( $b );
var_dump( $c );
var_dump( $d );
?>
|
Output:
IllegalArgumentExceptionobject(gfg)#1 (1) {
["value"]=>
string(13) "geeksforgeeks"
}
object(gfg)#2 (1) {
["value"]=>
int(1)
}
object(gfg)#3 (1) {
["value"]=>
array(2) {
["a"]=>
int(1)
["b"]=>
int(2)
}
}
object(gfg)#4 (1) {
["value"]=>
float(3.14)
}
Note: PHP has SplEnum class which can be used for enumerations, though the implementation is not available in all stable versions of PHP.
Last Updated :
24 Jan, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...