PHP get_​class() Function

What is PHP get_​class() Function?

If you want to know the class name from an object, use get_class() function.

Syntax:

get_class(object)

Parameters:

The Function has parameter which is required-

object (Required): It specifies the object whose class name  you want to know.

Return Values:

The function returns-

  • Class name of the object.
  • <?php
    class Human {
        public $name = 'John';
    }
    $theObj = new Human();
    echo get_class($theObj);
    ?>
    

    Output:

    The class name is: Human
  • An E_WARNING if the parameter is not an object.
  • Class name of the object if it is called inside a class method with the parameter $this.
  • <?php
    class Human {
        public $name = 'John';
        function eat(){
            echo "The class name is " . get_class($this);
        }
    }
    
    $theObj = new Human();
    $theObj->eat();
    ?>
    

    Output:

    The class name is: Human
  • Name of the child class if it is called from a child class.
  • <?php
    class Human {}
    class Adult extends Human {}
    $objAdult = new Adult();
    echo "The class name is:" . get_class($objAdult);
    ?>
    

    Output:

    The class name is: Adult

Practical Usages of get_​class() Function:

The function is very useful in debugging by identifying the class name of an object.

Alternative to get_class() function:

To get the parent class name use get_parent_class() function.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP get_​class() Function

get_class() is a class/object type function in PHP. It lets you know the class name from an object which is very helpful in debugging.

Reference:

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