Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Class/Object get_called_class() Function



The PHP Class/Object get_called_class() function is used to find the name of the class that called a static method. It is very useful when working with inheritance because it identifies the class that made the call rather than the class that defines the function.

Syntax

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

string get_called_class()

Parameters

This function does not accept any parameters.

Return Value

The get_called_class() function returns the name of the class from which the static method was called.

PHP Version

First introduced in core PHP 5.3.0, the get_called_class() function continues to function easily in PHP 7, and PHP 8.

Example 1

In this example, we define a simple class and use the PHP Class/Object get_called_class() function in a static method to display its name.

<?php
   // Define a class here
   class MyClass {
      public static function myFunc() {
          return get_called_class();
      }
   }
  
   echo MyClass::myFunc();
?>

Output

Here is the outcome of the following code −

MyClass

Example 2

In the below PHP code we will try to use the get_called_class() function and and see how this function works when a child class inherits from a parent class.

<?php
   // Define a class here
   class ParentClass {
      public static function myFunc() {
          return get_called_class();
      }
   }
  
   class ChildClass extends ParentClass {}
  
   echo ChildClass::myFunc();
?> 

Output

This will generate the below output −

ChildClass

Example 3

In this example, we use get_called_class() inside a trait to find the calling class. The trait's method myFunc() uses get_called_class() to precisely find the calling class, MyClass.

<?php
   trait MyTrait {
      public static function myFunc() {
          return get_called_class();
      }
  }
  
  class MyClass {
      use MyTrait;
  }
  
  echo MyClass::myFunc();
?> 

Output

This will create the below output −

MyClass

Example 4

This PHP code shows how the get_called_class() function reacts when different classes inherit from the same abstract class.

<?php
   // Define the abstract class here
   abstract class AbstractClass {
      public static function myFunc() {
          return get_called_class();
      }
   }
  
   class FirstClass extends AbstractClass {}
   class SecondClass extends AbstractClass {}
  
   echo FirstClass::myFunc();   
   echo SecondClass::myFunc(); 
?> 

Output

Following is the output of the above code −

FirstClass
SecondClass
php_function_reference.htm
Advertisements