PHP - Class/Object interface_exists() Function



The PHP Class/Object interface_exists() function is used to check if a given interface is defined or not. It returns true if the interface exists and false otherwise. This function is useful for checking that an interface is present before using it in the code.

Syntax

Here is the syntax of the PHP Class/Object interface_exists() function −

bool interface_exists(string $interface, bool $autoload = true)

Parameters

Below are the parameters of the interface_exists() function −

  • $interface − It is the name of the interface you want to check and it should be a string.

  • $autoload − It is the boolean value that defines whether the interface should be loaded automatically if it is still not specified then the default value is true.

Return Value

The interface_exists() function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

PHP Version

First introduced in core PHP 5.0.2, the interface_exists() function continues to function easily in PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Class/Object interface_exists() function to check if an interface named MyInterface exists.

<?php
   // Declare interface here
   interface MyInterface {}

   // Check using interface_exists method
   $result = interface_exists('MyInterface');

   //Display the result
   var_dump($result); 
?>

Output

Here is the outcome of the following code −

bool(true)

Example 2

In this example we will see what happens when checking for an interface using the interface_exists() method if the interface is not exist.

<?php
   // Check for nonexistent interface
   $result = interface_exists('NonExistentInterface');

   //Display the result
   var_dump($result); 
?> 

Output

This will generate the below output −

bool(false)

Example 3

Here, the function checks for an interface, and auto loading is enabled by default .

<?php
   spl_autoload_register(function ($interface) {
      if ($interface === 'AutoLoadedInterface') {
          eval('interface AutoLoadedInterface {}');
      }
  });
  
  $result = interface_exists('AutoLoadedInterface');
  var_dump($result); 
?> 

Output

This will create the below output −

bool(true)

Example 4

This example looks for an interface when autoloading is disabled, this means it will not be loaded if it is not already defined.

<?php
   spl_autoload_register(function ($interface) {
      if ($interface === 'AutoLoadedInterface') {
          eval('interface AutoLoadedInterface {}');
      }
  });
  
  $result = interface_exists('AutoLoadedInterface', false);
  var_dump($result); 
?> 

Output

Following is the output of the above code −

bool(false)
php_function_reference.htm
Advertisements