What is PHP enum_exists() Function?
If you want to check whether a defined enum has been declared or not, use PHP enum_exists() function.
What is enumeration (enum)?
In PHP, enumeration is a special data type that lets you define a fixed set of possible values for a variable. For example, in the following “Priority” is an enum and its defined cases are – “High”, ”Moderate”, and “Low”.
<?php
enum Priority: int {
case High = 3;
case Moderate = 2;
case Low = 1;
}
$role = Priority::Moderate;
echo $role->value;
?>
Syntax:
enum_exists(enum, autoload)
Parameters:
The Function has 1 required parameter and 1 optional parameter-
enum (Required): It specifies the name of the enum.
autoload (Optional): It specifies whether or not call the autoloader if the enum has not been loaded yet. The default value is TRUE.
- TRUE- If the value is TRUE, PHP will try to autoload the enum.
- FALSE – If the value is FALSE, PHP only check the already loaded enums.
Return Values:
The function returns-
- TRUE – if the enum has been defined.
- FALSE – if the enum hasn’t been defined.
Examples:
Example 1:
<?php
enum Priority1: int {
case High = 3;
case Moderate = 2;
case Low = 1;
}
if (enum_exists('Priority1') == TRUE){
echo "Enum 'Priority1' defined." . "<br />";
}else{
echo "Enum 'Priority1' not defined.";
}
if (enum_exists('Status') == TRUE){
echo "Enum 'Status' defined.";
}else{
echo "Enum 'Status' not defined.";
}
?>
Output:
Enum 'Priority1' defined.
Enum 'Status' not defined.
Notes on enum_exists() Function:
- The function checks the function name in case-insensitive manner. See the example below. Though the enum name is ‘priority2’, the enum_exists() function returns true for the enum name “pRIORITY2”.
<?php enum Priority2: int { case High = 3; case Moderate = 2; case Low = 1; } if (enum_exists('pRIORITY2') == TRUE){ echo "Enum 'Priority2' defined."; }else{ echo "Enum 'Priority2' not defined."; } ?>Output:
Enum 'Priority2' defined.
- An enum is a class in PHP.
PHP Version Support:
PHP 8 >= 8.1.0
Summary: PHP enum_exists() Function
enum_exists() is a built-in classes/object function in PHP. The enum_exists() is a handy way to check whether an enum defined before using it and getting a fatal error.