Skip to content

Instantly share code, notes, and snippets.

@carbolymer
Created July 30, 2010 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carbolymer/500728 to your computer and use it in GitHub Desktop.
Save carbolymer/500728 to your computer and use it in GitHub Desktop.
<?php
namespace enum;
function Create($sName,$aValues, $sNamespace = __NAMESPACE__)
{
if(preg_match("#[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*#si",$sName) === 0)
throw new InvalidName;
if(class_exists('\enum\\'.$sName))
throw new NameExists;
$sValues = 'array(';
foreach($aValues as $sValue)
{
$sValues .= '\''.sha1($sName.'_'.time().'_'.$sValue).'\' => \''.$sValue.'\', ';
}
$sValues = substr($sValues, 0, -2);
$sValues .= ')';
$_class = '
namespace '.$sNamespace.';
class '.$sName.'
{
private static $_aValues = '.$sValues.';
private $_sCurrentValue = null;
public function __construct($sName)
{
if(in_array($sName,self::$_aValues))
{
foreach(self::$_aValues as $sKey => $sValue)
if($sValue == $sName)
$this->_sCurrentValue = $sKey;
}
else
throw new TypeDoesNotMatch();
}
public function __toString()
{
return self::$_aValues[$this->_sCurrentValue];
}
}';
eval($_class);
}
class TypeDoesNotMatch extends \Exception {};
class InvalidName extends \Exception {};
class NameExists extends \Exception {};
// przyklady:
\enum\Create ('method',array('get','post'), __NAMESPACE__);
\enum\Create ('input_type', array('button', 'checkbox', 'file', 'hidden', 'image', 'password', 'radio', 'reset', 'submit', 'text'), __NAMESPACE__);
use \Form\method;
use \Form\input_type;
$oMethod = new method('GET');
$oInput = new input_type('button');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment