PHP - Class/Object class_exists() Function
The PHP Class/Object class_exists() function is used to check if the given class have been defined. It returns TRUE if class_name is a defined class, FALSE otherwise. This function is useful when you have to check whether a class is available before trying to create an object of it or interact with it in any way.
Syntax
Below is the syntax of the PHP Class/Object class_exists() function −
bool class_exists ( string $class_name , bool $autoload );
Parameters
Below are the parameters of the class_exists() function −
$class_name − It is the class name. The name is matched case insensitively.
$autoload − Optional. If true, the function will try to autoload the class if it has not yet been declared. Defaults to true.
Return Value
The class_exists() function returns true if the class exists, and FALSE on failure.
PHP Version
First introduced in core PHP 4, the class_exists() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
First we will use the PHP Class/Object class_exists() function to show the basic usage and check if a class named MyClass exists.
<?php
// Declare class here
class MyClass {}
// Check of the class exists or not
if (class_exists('MyClass')) {
echo "MyClass exists!";
} else {
echo "MyClass does not exist.";
}
?>
Output
This will generate the below output −
MyClass exists!
Example 2
This example checks for a class called NonDeclaredClass, which has not been defined. So check if this class exists using the class_exists() function.
<?php
// If the class does not exist
if (class_exists('NonDeclaredClass')) {
echo "NonDeclaredClass exists!";
} else {
echo "NonDeclaredClass does not exist.";
}
?>
Output
Here is the outcome of the following code −
NonDeclaredClass does not exist.
Example 3
This example shows the autoloading functionality by trying to see a class that can be autoloaded using the class_exists() function.
<?php
// Register an autoload function
spl_autoload_register(function($className) {
// Check if the class name is 'AutoLoadedClass'
if ($className == 'AutoLoadedClass') {
eval('class AutoLoadedClass {}');
}
});
if (class_exists('AutoLoadedClass')) {
echo "AutoLoadedClass exists!";
} else {
echo "AutoLoadedClass does not exist.";
}
?>
Output
This will create the below output −
AutoLoadedClass exists!
Example 4
Using the class_exists() function in the below example to disable autoloading if the class is not declared yet and it returns a false value.
<?php
if (class_exists('AutoLoadedClass', false)) {
echo "AutoLoadedClass exists!";
} else {
echo "AutoLoadedClass does not exist.";
}
?>
Output
Following is the output of the above code −
AutoLoadedClass does not exist.