PHP中Enum(枚举)用法实例详解
本文实例讲述了PHP中Enum(枚举)用法。分享给大家供大家参考,具体如下:
PHP其实有Enum类库的,需要安装perl扩展,所以不是php的标准扩展,因此代码的实现需要运行的php环境支持。
(1)扩展类库SplEnum类。该类的摘要如下:
SplEnumextendsSplType{
/*Constants*/
constNULL__default=null;
/*方法*/
publicarraygetConstList([bool$include_default=false])
/*继承的方法*/
SplType::__construct([mixed$initial_value[,bool$strict]])
}
使用示例:
<?php
classMonthextendsSplEnum{
const__default=self::January;
constJanuary=1;
constFebruary=2;
constMarch=3;
constApril=4;
constMay=5;
constJune=6;
constJuly=7;
constAugust=8;
constSeptember=9;
constOctober=10;
constNovember=11;
constDecember=12;
}
echonewMonth(Month::June).PHP_EOL;
try{
newMonth(13);
}catch(UnexpectedValueException$uve){
echo$uve->getMessage().PHP_EOL;
}
?>
输出结果:
6 ValuenotaconstinenumMonth
(2)自定义的Enum类库
<?php
/**
*AbstractclassthatenablescreationofPHPenums.Allyou
*havetodoisextendthisclassanddefinesomeconstants.
*Enumisanobjectwithvaluefromonofthoseconstants
*(orfromonofsuperclassifany).Thereisalso
*__defaultconstatthatenablesyoucreationofobject
*withoutpassingenumvalue.
*
*@authorMarijanŠuflaj<msufflaj32@gmail.com>
*@linkhttp://php4every1.com
*/
abstractclassEnum{
/**
*Constantwithdefaultvalueforcreatingenumobject
*/
const__default=null;
private$value;
private$strict;
privatestatic$constants=array();
/**
*Returnslistofalldefinedconstantsinenumclass.
*Constantsvalueareenumvalues.
*
*@parambool$includeDefaultIftrue,defaultvalueisincludedintoreturn
*@returnarrayArraywithconstantvalues
*/
publicfunctiongetConstList($includeDefault=false){
$class=get_class($this);
if(!array_key_exists($class,self::$constants)){
self::populateConstants();
}
return$includeDefault?array_merge(self::$constants[__CLASS_],array(
"__default"=>self::__default
)):self::$constants[__CLASS_];
}
/**
*Createsnewenumobject.Ifchildclassoverrides__construct(),
*itisrequiredtocallparent::__construct()inorderforthis
*classtoworkasexpected.
*
*@parammixed$initialValueAnyvaluethatisexistsindefinedconstants
*@parambool$strictIfsettotrue,typeandvaluemustbeequal
*@throwsUnexpectedValueExceptionIfvalueisnotvalidenumvalue
*/
publicfunction__construct($initialValue=null,$strict=true){
$class=get_class($this);
if(!array_key_exists($class,self::$constants)){
self::populateConstants();
}
if($initialValue===null){
$initialValue=self::$constants[$class]["__default"];
}
$temp=self::$constants[$class];
if(!in_array($initialValue,$temp,$strict)){
thrownewUnexpectedValueException("Valueisnotinenum".$class);
}
$this->value=$initialValue;
$this->strict=$strict;
}
privatefunctionpopulateConstants(){
$class=get_class($this);
$r=newReflectionClass($class);
$constants=$r->getConstants();
self::$constants=array(
$class=>$constants
);
}
/**
*Returnsstringrepresentationofanenum.Defaultsto
*valuecastedtostring.
*
*@returnstringStringrepresentationofthisenum'svalue
*/
publicfunction__toString(){
return(string)$this->value;
}
/**
*Checksiftwoenumsareequal.Onlyvalueischecked,notclasstypealso.
*Ifenumwascreatedwith$strict=true,thenstrictcomparisonapplies
*herealso.
*
*@returnboolTrueifenumsareequal
*/
publicfunctionequals($object){
if(!($objectinstanceofEnum)){
returnfalse;
}
return$this->strict?($this->value===$object->value)
:($this->value==$object->value);
}
}
使用示例如下:
classMyEnumextendsEnum{
constHI="Hi";
constBY="By";
constNUMBER=1;
const__default=self::BY;
}
var_dump(newMyEnum(MyEnum::HI));
var_dump(newMyEnum(MyEnum::BY));
//Use__default
var_dump(newMyEnum());
try{
newMyEnum("Idon'texist");
}catch(UnexpectedValueException$e){
var_dump($e->getMessage());
}
输出结果如下:
object(MyEnum)#1(2){
["value":"Enum":private]=>
string(2)"Hi"
["strict":"Enum":private]=>
bool(true)
}
object(MyEnum)#1(2){
["value":"Enum":private]=>
string(2)"By"
["strict":"Enum":private]=>
bool(true)
}
object(MyEnum)#1(2){
["value":"Enum":private]=>
string(2)"By"
["strict":"Enum":private]=>
bool(true)
}
string(27)"ValueisnotinenumMyEnum"
希望本文所述对大家PHP程序设计有所帮助。