PHP Function Reference

PHP class_exists() Function



The PHP class_exists() function is used to check whether or not the given class has been defined. It returns true if the given class is defined, else returns false.

Syntax

class_exists(class, autoload)

Parameters

class Required. Specify the class name to check. The name is matched in a case-insensitive manner.
autoload Optional. Specify whether to call __autoload or not by default.

Return Value

Returns true if class is a defined class, false otherwise.

Example: class_exists() example

The example below shows the usage of class_exists() function.

<?php
//checking that the class exists 
//before trying to use it
if (class_exists('MyClass')) {
  $MyObj = new MyClass();
  echo "An object of class 'MyClass' is created.";
} else {
  echo "'MyClass' do not exist!.";
}
?>

The output of the above code will be:

'MyClass' do not exist!.

Example: using autoload parameter

The example below shows how to use autoload parameter with this function.

<?php
spl_autoload_register(function ($class_name) {
  include $class_name.'.php';

  //checking to see whether the 
  //include declared the class
  if (!class_exists($class_name, false)) {
    throw new LogicException("Unable to load class: $class_name");
  }
});

if (class_exists(MyClass::class)) {
  $MyObj = new MyClass();
}
?>

❮ PHP Classes/Objects Reference