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
get_called_class();
Example
Let's create two classes and call a method from the child class:
<?php
class ParentClass {
public static function test() {
return get_called_class();
}
}
class ChildClass extends ParentClass {}
echo ChildClass::test();
?>
Execution result:
'ChildClass'
Example
Let's check the function's operation when called from the parent class:
<?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:
'A'
'B'
Example
Using the function to create objects of the required class:
<?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:
'Product'
See Also
-
the get_class function,
which returns the object's class -
the get_parent_class function,
which returns the parent class