Skip to content

Instantly share code, notes, and snippets.

@rafageist rafageist/Enum.php
Last active Jul 25, 2019

Embed
What would you like to do?
PHP Enum Solution
<?php
/**
* This is a trick or solution for create enumerations in PHP using classes
* If you are curious you will realize that you can build a hierarchy of
* enumerations, even give other uses to those classes.
*
* @author rafageist
*/
// Variant 1: Create a that simple abstract class (with or without namespace) ...
// ... I like namespaces
namespace Enums {
abstract class Enum {
public function __toString() {
return get_class($this); // the name of the class is the value !!
}
}
// create enum as abstract class
abstract class Temperature extends Enum {}
// create the items as classes
class HOT extends Temperature {}
class COLD extends Temperature {}
}
// Variant 2: with traits
/*
namespace Enums {
trait Enum {
public function __toString() {
return get_class($this); // the name of the class is the value !!
}
}
// create your enum
abstract class Temperature {}
// create the items of your enum
class HOT extends Temperature { use Enum; }
class COLD extends Temperature { use Enum; }
}
*/
<?php
include "Enums.php";
use Enums;
function doSome(Temperature $data){
echo $data."\n";
if ($data instanceof HOT) echo "is hot\n";
if ($data instanceof COLD) echo "is cold\n";
if ($data == 'HOT') echo "super hot \n";
if ($data == 'COLD') echo "super cold \n";
switch($data) {
case 'HOT':
echo "1 is case of hot\n";
break;
case 'COLD':
echo "1 is case of cold\n";
break;
}
switch($data) {
case HOT::class:
echo "2 is case of hot\n";
break;
case COLD::class:
echo "2 is case of cold\n";
break;
}
switch(true) {
case $data instanceof HOT:
echo "3 is case of hot !!\n";
break;
case $data instanceof COLD:
echo "3 is case of cold !!\n";
break;
}
}
doSome(new HOT());
doSome(new COLD());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.