Examples of enum (enum) usages in PHP _php tips

Source: Internet
Author: User
Tags getmessage

The examples in this article describe the use of enum (enum) in PHP. Share to everyone for your reference, specific as follows:

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

(1) Extended class library Splenum class. The summary of the class is as follows:

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

Use examples:

<?php
class 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 =.
echo New Month (Month::june). Php_eol;
try {
  new Month;
} catch (Unexpectedvalueexception $uve) {
  echo $uve->getmessage (). Php_eol
}
? >

Output results:

6
Value not a const in enum Month

(2) Custom enum class Library

<?php/** * Abstract class that enables creation of PHP enums.
 All your * have to be extend this class and define some constants. * The Enum is a object with value ' from ' to ' those constants * (or from of superclass if any).
 There is also * __default constat This enables you creation of object * without passing enum value.
   * * @author Marijanšuflaj <msufflaj32@gmail.com> * @link http://php4every1.com/abstract class Enum {/**
  * Constant with 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 are enum values. * * @param bool $includeDefault If True, default value is included to return * @return array array with constant V
    Alues */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 (), * The It is required to call Parent::__construct
   Work as expected. * * @param mixed $initialValue Any value of the exists in defined constants * @param bool $strict If set to True, T  Ype and value must be equal * @throws unexpectedvalueexception If value are not valid Enum value/Public function
    __construct ($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 in enum".)
    $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
  ) $this->value; }/** * Checks If two enums are equal.
   Only the value is checked and not class type also.
   * If enum is created with $strict = True, then strict comparison applies * here also. * * @return bool True If enums are equal/Public function equals ($object) {if (!) (
    $object instanceof Enum)) {return false; Return $this->strict? ($this->value = = $objEct->value): ($this->value = = $object->value);

 }
}

Use the example below:

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 __default
var_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 '

I hope this article will help you with the PHP program design.

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.