Tips for using enum in PHP

Source: Internet
Author: User
Tags getmessage install perl
This article mainly introduces the use of enum in PHP skills, interested in the reference of friends, I hope to help you.

PHP actually has enum class library, need to install Perl extension, so it is not PHP standard extension, so the implementation of code needs to run PHP environment support.

(1) Extend class library Splenum class. The summary of this class is as follows:

Splenum extends Spltype {/* Constants */const NULL __default = null;/* Method */public array getconstlist ([bool $include _de Fault = false]//* Inherited method */spltype::__construct ([Mixed $initial _value [, BOOL $strict])}

Examples of Use:

<?phpclass Month extends Splenum {  const __default = self::january;  const January = 1;  const February = 2;  Const MARCH = 3;  Const APRIL = 4;  Const MAY = 5;  Const June = 6;  Const July = 7;  const August = 8;  const SEPTEMBER = 9;  Const OCTOBER = ten;  Const November = one;  Const December = 12;} echo New Month (Month::june). php_eol;try {  new Month;} catch (Unexpectedvalueexception $uve) {  echo $uve->getmessage (). Php_eol;}? >

Output Result:

6Value not a const in enum Month

(2) Custom enum class Library

<?php/** * Abstract class that enables creation of PHP enums. All of you * are extend this class and define some constants. * Enum is a object with value from the those constants * (or from on in superclass if any). There is also * __default constat, enables you creation of object * without passing enum value. * * @author Marijanšuflaj <msufflaj32@gmail.com&gt * @link http://php4every1.com */abstract class Enum {/** *  Constant with the default value for creating enum Object */const __DEFAULT = null;  Private $value;  Private $strict;  private static $constants = Array ();   /** * Returns List of all defined constants in Enum class.   * Constants value is enum values. * * @param bool $includeDefault If True, default value is included to return * @return array array with constant Val    UES */Public Function getconstlist ($includeDefault = False) {$class = Get_class ($this); if (!array_key_exists ($class, Self:: $constants))} {self::p OpulatecOnstants (); } return $includeDefault?  Array_merge (self:: $constants [__class_], Array ("__default" = Self::__default)): Self:: $constants [__class_]; }/** * Creates new Enum object. If Child class overrides __construct (), * It's required to call Parent::__construct () on order for this * class to Wo   RK as expected. * * @param mixed $initialValue Any value of exists in defined constants * @param bool $strict If set to True, Typ E and value must be equal * @throws unexpectedvalueexception If value are not valid enum value */Public function __co    NStruct ($initialValue = null, $strict = True) {$class = Get_class ($this);    if (!array_key_exists ($class, Self:: $constants)) {self::p opulateconstants ();    if ($initialValue = = = null) {$initialValue = self:: $constants [$class] [__default];    } $temp = self:: $constants [$class]; if (!in_array ($initialValue, $temp, $strict)) {throw new Unexpectedvalueexception ("Value is not inEnum ".    $class);    } $this->value = $initialValue;  $this->strict = $strict;    } Private Function Populateconstants () {$class = Get_class ($this);    $r = new Reflectionclass ($class);    $constants = $r->getconstants ();  Self:: $constants = Array ($class = = $constants); }/** * Returns string representation of an enum.   Defaults to * value casted to string. * * @return String string representation of this enum ' s value */Public Function __tostring () {return (string) $t  his->value; }/** * Checks if the enums is equal.   Only value was checked, not class type also.   * If enum is created with $strict = True and then strict comparison applies * here also. * * @return bool True If enums is equal */Public function equals ($object) {if (!    $object instanceof Enum) {return false; } return $this->strict?  ($this->value = = = $object->value): ($this->value = = $object->value); }}

Examples of use are:

Class MyEnum extends Enum {  const HI = "HI";  Const by = ' by ';  Const NUMBER = 1;  Const __DEFAULT = Self::by;} Var_dump (New MyEnum (Myenum::hi)); Var_dump (new MyEnum (Myenum::by));//use __defaultvar_dump (New MyEnum ()); try {  New MyEnum ("I don ' t exist");} catch (Unexpectedvalueexception $e) {  var_dump ($e->getmessage ());}

The output results are as follows:

Object (MyEnum) #1 (2) {["Value": "Enum":p rivate]=> string (2) "Hi" ["Strict": "enum":p rivate]=> bool (true)}object ( MyEnum) #1 (2) {["Value": "Enum":p rivate]=> string (2) "by" ["Strict": "enum":p rivate]=> bool (true)}object (MyEnum) #1 (2) {["Value": "Enum":p rivate]=> string (2) "by" ["Strict": "enum":p rivate]=> bool (TRUE)}string (+) "value is not in enum MyEnum "

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.