PHP - Class/Object enum_exists() Function



The PHP Class/Object enum_exists() function is used to determine that a specific enum type exists. It returns true if the enum is defined and false otherwise. This function is useful for verifying that an enum is defined before using it. It also saves unexpected errors.

Syntax

Below is the syntax of the PHP Class/Object enum_exists() function −

bool enum_exists ( string $enum, bool $autoload = true )

Parameters

Below are the parameters of the enum_exists() function −

  • $enum − It is the name of the enum you want to check.

  • $autoload − It is an optional parameter. If set to true, it will attempt to autoload the enum class if it is not present. Default value is true.

Return Value

The enum_exists() function returns TRUE if enum is a defined enum, FALSE on failure.

PHP Version

First introduced in core PHP 8.1.0, the enum_exists() function continues to function easily in after versions.

Example 1

Here is the basic example of the PHP Class/Object enum_exists() function to check that the simple enum named Bike exists.

<?php
   // Define enum here
   enum Bike { 
      case Petrol; 
      case Electric; 
   } 
   
   if(enum_exists(Bike::class)){ 
      echo "Bike enum is defined." ; 
   } else { 
      echo "Bike enum is not defined." ; 
   } 
?>

Output

Here is the outcome of the following code −

Bike enum is defined.

Example 2

In this example we are going to use enum_exists() function to check if the enum exists for the non existent enum. So in this case the function will return false.

<?php
   // Check for enum
   if(enum_exists(Fruits::class)){ 
      echo "Fruits enum is defined" ; 
   } else { 
      echo "Fruits enum is not defined" ; 
   } 
?> 

Output

This will generate the below output −

Fruits enum is not defined

Example 3

Now the below code checks for an enum inside a specific namespace with the help of enum_exists(), and prints the result.

<?php
   // Define enum namespace
   namespace App\Enums;

   enum UserStatus {
       case Admin;
       case User;
   }
   
   var_dump(enum_exists('App\Enums\UserStatus'));  
?> 

Output

This will create the below output −

bool(true)

Example 4

In the following example, we are using the enum_exists() function to check if a simple enum called Status exists.

<?php
   // Define enum here
   enum Status {
      case Active;
      case Inactive;
   }
  
   var_dump(enum_exists('Status'));  
?> 

Output

Following is the output of the above code −

bool(true)
php_function_reference.htm
Advertisements