PHP에서 Enum(열거) 사용법에 대한 자세한 설명

怪我咯
풀어 주다: 2023-03-13 22:38:01
원래의
14074명이 탐색했습니다.

열거는 정수 상수의 모음입니다. 열거는 일상 생활에서 매우 일반적입니다.

예를 들어, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,

SATURDAY는 요일을 나타내는 열거형입니다.

열거에 대한 설명은 구조체 및 공용체와 유사하며 그 형식은 다음과 같습니다.

enum 열거 이름 {(열거 값 테이블)

identifier [= 정수 상수],

identifier [= 정수 상수] ,

...

식별자 [=정수상수],

} 열거변수;

열거가 초기화되지 않은 경우, 즉 "=정수상수"가 생략된 경우 첫 번째 식별자는 0, 1, 2를 할당하여 시작 , ... 식별자에

번. 그러나 열거 값 테이블의 구성원에 값이 할당되면 후속 구성원은 순서대로 1을 더하는 규칙에 따라 해당 값을 결정합니다.

이 문서의 예제에서는 PHP의 Enum(열거) 사용법을 설명합니다. 참조를 위해 모든 사람과 공유하십시오. 세부 사항은 다음과 같습니다.

PHP에는 실제로 Perl 확장 설치가 필요한 Enum 클래스 라이브러리가 있으므로 이는 PHP의 표준 확장이 아니므로 코드 구현에는 다음이 필요합니다. 실행 중인 PHP 환경을 지원합니다.

(1) 클래스 라이브러리 SplEnum 클래스를 확장합니다. 이 클래스의 요약은 다음과 같습니다.

SplEnum extends SplType {
/* Constants */
const NULL default = null ;
/* 方法 */
public array getConstList ([ bool $include_default = false ] )
/* 继承的方法 */
SplType::construct ([ mixed $initial_value [, bool $strict ]] )
}
로그인 후 복사

사용 예

:

출력 결과:

6
Value not a const in enum Month
로그인 후 복사

(2) 맞춤형 Enum 클래스 라이브러리

<?php
/**
 * Abstract class that enables creation of PHP enums. All you
 * have to do is extend this class and define some constants.
 * Enum is an object with value from on of those constants
 * (or from on of superclass if any). There is also
 * default constat that 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 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 into return
   * @return array Array with constant values
   */
  public function getConstList($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_];
  }
  /**
   * Creates new enum object. If child class overrides construct(),
   * it is required to call parent::construct() in order for this
   * class to work as expected.
   *
   * @param mixed $initialValue Any value that is exists in defined constants
   * @param bool $strict If set to true, type and value must be equal
   * @throws UnexpectedValueException If value is not valid enum value
   */
  public function 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)) {
      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&#39;s value
   */
  public function toString() {
    return (string) $this->value;
  }
  /**
   * Checks if two enums are equal. Only value is checked, not class type also.
   * If enum was 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);
  }
}
로그인 후 복사

사용 예는 다음과 같습니다.

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&#39;t exist");
} catch (UnexpectedValueException $e) {
  var_dump($e->getMessage());
}
로그인 후 복사

출력 결과는 다음과 같습니다. :

아아아아

위 내용은 PHP에서 Enum(열거) 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!