array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'es', ), 'this' => array ( 0 => 'language.enumerations.examples.php', 1 => 'Ejemplos', ), 'up' => array ( 0 => 'language.enumerations.php', 1 => 'Enumerations', ), 'prev' => array ( 0 => 'language.enumerations.object-differences.inheritance.php', 1 => 'Why enums aren\'t extendable', ), 'next' => array ( 0 => 'language.errors.php', 1 => 'Errores', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'language/enumerations.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
Ejemplo #1 Basic limited values
<?php
enum SortOrder
{
case Asc;
case Desc;
}
function query($fields, $filter, SortOrder $order = SortOrder::Asc)
{
/* ... */
}
?>
The query()
function can now proceed safe in the knowledge that
$order
is guaranteed to be either SortOrder::Asc
or SortOrder::Desc
. Any other value would have resulted in a
TypeError, so no further error checking or testing is needed.
Ejemplo #2 Advanced exclusive values
<?php
enum UserStatus: string
{
case Pending = 'P';
case Active = 'A';
case Suspended = 'S';
case CanceledByUser = 'C';
public function label(): string
{
return match($this) {
static::Pending => 'Pending',
static::Active => 'Active',
static::Suspended => 'Suspended',
static::CanceledByUser => 'Canceled by user',
};
}
}
?>
In this example, a user's status may be one of, and exclusively, UserStatus::Pending
,
UserStatus::Active
, UserStatus::Suspended
, or
UserStatus::CanceledByUser
. A function can type a parameter against
UserStatus
and then only accept those four values, period.
All four values have a label()
method, which returns a human-readable string.
That string is independent of the "machine name" scalar equivalent string, which can be used in,
for example, a database field or an HTML select box.
<?php
foreach (UserStatus::cases() as $case) {
printf('<option value="%s">%s</option>\n', $case->value, $case->label());
}
?>