PHP - Class/Object get_class() Function



The PHP Class/Object get_class() function is used to get the name of the class to which an object belongs. This function is handy for debugging or when working with many classes and needs to find the class of a given object while execution.

Syntax

Below is the syntax of the PHP Class/Object get_class() function −

string get_class ( object $object = ? )

Parameters

This function accepts $object parameter which is the tested object.

Return Value

The get_class() function returns the name of the class as a string.

PHP Version

First introduced in core PHP 4, the get_class() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Class/Object get_class() function to get the name of the class of an object.

<?php
   // Declare Car class here
   class Car {
   }
   
   $myCar = new Car();
   echo "The class name is : ".get_class($myCar);
?>

Output

Here is the outcome of the following code −

The class name is : Car

Example 2

This example shows how get_class() function returns the class name of an object, even if it is an instance of a child class.

<?php
   // Declare Animal class here
   class Animal {
   }
   
   class Dog extends Animal {
   }
   
   $myDog = new Dog();
   echo "Get the class name: ".get_class($myDog);
?> 

Output

This will generate the below output −

Get the class name: Dog

Example 3

Now the below code retrieves name of the class using the get_class() function, and prints it.

<?php
   class f1 {
      function f1() {
         // implements some logic
      }
      
      function name() {
         echo "My name is " , get_class($this) , "\n";
      }
   }
	
   // create an object
   $bar = new f1();
   
   // external call
   echo "Its name is " , get_class($bar) , "\n";
   
   // internal call
   $bar->name();
?> 

Output

This will create the below output −

Its name is f1
My name is f1
php_function_reference.htm
Advertisements