Created
July 30, 2010 15:34
-
-
Save carbolymer/500728 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment