Detaillierte Erläuterung der Verwendung von Enum (Aufzählung) in PHP

怪我咯
Freigeben: 2023-03-13 22:38:01
Original
14075 Leute haben es durchsucht

Eine Aufzählung ist eine Sammlung ganzzahliger Konstanten. Aufzählungen kommen im täglichen Leben sehr häufig vor.

Zum Beispiel ist SONNTAG, MONTAG, DIENSTAG, MITTWOCH, DONNERSTAG, FREITAG,

SAMSTAG, der die Woche darstellt, eine Aufzählung.

Die Beschreibung der Aufzählung ähnelt der Struktur und Vereinigung und hat die Form:

Name der Aufzählungsaufzählung {(Tabelle der Aufzählungswerte)

Bezeichner [= Ganzzahlkonstante ],

Identifier[=Integer-Konstante],

...

Identifier[=Integer-Konstante],

} enum Variable;

Wenn die Aufzählung nicht initialisiert ist, d. h. wenn „=Ganzzahlkonstante“ weggelassen wird, weisen Sie beginnend mit dem ersten Bezeichner 0, 1, 2,… zu. Wenn jedoch einem Mitglied in der Aufzählungswerttabelle ein Wert zugewiesen wird, bestimmen die nachfolgenden Mitglieder ihren Wert gemäß der Regel

plus 1.

Die Beispiele in diesem Artikel beschreiben die Verwendung von Enum (Aufzählung) in PHP. Teilen Sie es als Referenz mit allen. Die Details lauten wie folgt:

PHP verfügt tatsächlich über die Enum-Klassenbibliothek, für die die Installation der Perl-Erweiterung erforderlich ist. Es handelt sich also nicht um eine Standarderweiterung von PHP, also um die Implementierung Die Ausführung des Codes erfordert die Unterstützung der laufenden PHP-Umgebung.

(1) Erweitern Sie die SplEnum-Klasse der Klassenbibliothek. Die Zusammenfassung dieser Klasse lautet wie folgt:

SplEnum extends SplType {
/* Constants */
const NULL default = null ;
/* 方法 */
public array getConstList ([ bool $include_default = false ] )
/* 继承的方法 */
SplType::construct ([ mixed $initial_value [, bool $strict ]] )
}
Nach dem Login kopieren
Verwendungsbeispiel

:

Ausgabeergebnis:
<?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 = 10;
  const November = 11;
  const December = 12;
}
echo new Month(Month::June) . PHP_EOL;
try {
  new Month(13);
} catch (UnexpectedValueException $uve) {
  echo $uve->getMessage() . PHP_EOL;
}
?>
Nach dem Login kopieren

(2 ) Anpassung Das Verwendungsbeispiel der Enum-Klassenbibliothek
6
Value not a const in enum Month
Nach dem Login kopieren

lautet wie folgt:
<?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);
  }
}
Nach dem Login kopieren

Das Ausgabeergebnis lautet wie folgt:
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());
}
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonDetaillierte Erläuterung der Verwendung von Enum (Aufzählung) in PHP. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!