The get_called_class Function

The get_called_class function returns the name of the class in whose context a static method was called. This is useful when working with inheritance, when you need to determine from which specific class a method was called.

Syntax

phpget_called_class();

Example

Let's create two classes and call a method from the child class:

php<?php
  class ParentClass {
    public static function test() {
      return get_called_class();
    }
  }

  class ChildClass extends ParentClass {}

  echo ChildClass::test();
?>

Execution result:

php'ChildClass'

Example

Let's check the function's operation when called from the parent class:

php<?php
  class A {
    public static function who() {
      return get_called_class();
    }
  }

  class B extends A {}

  echo A::who();
  echo "\n";
  echo B::who();
?>

Execution result:

php'A'
'B'

Example

Using the function to create objects of the required class:

php<?php
  class Factory {
    public static function create() {
      $class = get_called_class();
      return new $class;
    }
  }

  class Product extends Factory {}

  $obj = Product::create();
  echo get_class($obj);
?>

Execution result:

php'Product'

See Also