What is PHP class_exists() Function?
If you want to check whether a class has been defined in your current script execution, use class_exists() function.
Syntax:
class_exists(class_name, autoload)
Parameters:
The Function has 1 required parameter and 1 optional parameter-
class_name (Required): It specifies the class name.
autoload (Optional): It determines whether to call the autoloader if the original class is not found. It can take 2 values-
- TRUE – it is the default value. It indicates that autoloader should be called if the original class is not found.
- FALSE – It indicates that autoloader should not be called if the original class is not found.
Return Values:
The function returns-
- TRUE if the class name is defined.
- FALSE if the class name is not defined.
Examples:
Example:
<?php
class Human {
public $name = 'John';
}
if (class_exists('Human')) {
echo "Class \"Human\" found.";
}else{
echo "Class \"Human\" not found.";
}
?>
Output:
Class "Human" found.
Practical Usages of class_exists() Function:
- This function is primarily used to avoid “Class not found” fatal error by verifying whether the class is already defined before using it.
- In MVC framework, before loading a controller class, developers use class_exists() function to check if the classt really exists.
- In WordPress, developers use class_exists() function to check whether a plugin or library exists.
Notes on class_exists() Function:
The function class_exists() is case-insensitive. This means the function can find a class whose name is same but case is different. See example-
<?php
class Human {
public $name = 'John';
}
echo "Original class name is: \"Human\". <br />";
if (class_exists('Human')) {
echo "class_exists() function found a class, named: \"HUMAN\". <br />";
}
?>
Output:
Original class name is: "Human".
class_exists() function found a class, named: "HUMAN".
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP class_exists() Function
class_exists() is a class/object type function in PHP. Developers frequently use this function to determine a class existence before proceeding.