Skip to content

Instantly share code, notes, and snippets.

@FabioBatSilva
Created August 6, 2012 15:49
Show Gist options
  • Save FabioBatSilva/3275815 to your computer and use it in GitHub Desktop.
Save FabioBatSilva/3275815 to your computer and use it in GitHub Desktop.
Type-safe enumeration class.
<?php
class DirectionEnum extends Enum
{
const NORTH = 'NORTH';
const SOUTH = 'SOUTH';
const EAST = 'EAST';
const WEST = 'WEST';
/**
* @return boolean
*/
public function isCold()
{
return $this === self::NORTH();
}
}
class MyNavigator
{
public function setDirection(DirectionEnum $direction)
{
echo "Going to : " . $direction . PHP_EOL;
if ($direction->isCold()) {
echo "It's could !!" . PHP_EOL;
}
}
}
$south = DirectionEnum::SOUTH();
var_dump($south === DirectionEnum::SOUTH());
// bool(true)
var_dump((string)$south === DirectionEnum::SOUTH);
// bool(true)
var_dump($south->valueOf() === DirectionEnum::SOUTH);
// bool(true)
$navigator = new MyNavigator();
$navigator->setDirection(DirectionEnum::EAST());
// Going to : EAST
$navigator->setDirection(DirectionEnum::NORTH());
// Going to : NORTH
// It's could !!
<?php
/**
* Enum
*
* Type-safe enumerations.
* An alternative to the simple string or integer constants to represent sets of related items.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class Enum
{
/**
* Enumeration value
*
* @var mixed
*/
protected $value;
/**
* @var Enumeration instances
*/
static protected $instances;
/**
* Enumeration construct
*
* @param mixed $value
*/
protected function __construct($value)
{
$this->value = $value;
}
/**
* Returns the enumeration value as string
*
* @return string
*/
public function __toString()
{
return (string) $this->value;
}
/**
* Returns the enumeration value
*
* @return string
*/
public function valueOf()
{
return $this->value;
}
/**
* Returns an enumeration instance
*
* @param string $name Literal enumeration declaration
* @param array $args Unused method args
* @return Enum
*
* @throws \InvalidArgumentException
*/
public static function __callStatic($name, $args)
{
if (isset(self::$instances[$name])) {
return self::$instances[$name];
}
$class = get_called_class();
if ( ! defined($class . '::' . $name)) {
throw new \InvalidArgumentException("Undefined enumeration value \"{$name}\"");
}
if ( ! empty($args)) {
throw new \InvalidArgumentException("Enumeration method for \"{$name}\" does not accept any value");
}
return self::$instances[$name] = new $class(constant($class . '::' . $name));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment