Open In App

PHP | class_exists() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The class_exists() function is an inbuilt function in PHP which is used to check whether the given class is defined or not.

Syntax:

bool class_exists( string $class_name, bool $autoload = TRUE )

Parameters: This function accept two parameters as mentioned above and described below:

  • $class_name: It holds the class name which need to check their existence.
  • $autoload: It checks whether the __autoload is called or not by default.

Return Value: This function returns True if class name is defined otherwise returns False.

Below programs illustrate the class_exists() function in PHP:

Program 1:




<?php
  
// Create a class
class GFG {
    public $Geek_name = "Welcome to GeeksforGeeks"
  
// Check class name exist or not
if(class_exists('GFG')) {
    echo "Class name exists";
}
else {
    echo "Class name does not exist";
}
  
?>


Output:

Class name exists

Program 2:




<?php
  
// Creating class 
class GFG { 
    public $data1
    public $data2
    public $data3
}
  
if(class_exists('GFG')) {
  
    // Creating an object 
    $obj = new GFG();
  
    // Set values of $obj object 
    $obj->data1 = "Geeks"
    $obj->data2 = "for"
    $obj->data3 = "Geeks"
  
    // Print values of $obj object 
    echo "$obj->data1  \n$obj->data2  \n$obj->data3"
}
else {
    echo "Class does not exist";
}
  
?>


Output:

Geeks  
for  
Geeks

Reference: https://www.php.net/manual/en/function.class-exists.php



Last Updated : 27 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads