PHP get_called_class() Function

What is PHP get_called_class() Function?

If a static method inside a class or trait is called from outside another class and you want to know the name of that calling class, use PHP get_called_class() function.

By default, when you call a static method in an inherited class, PHP considers the call happened from the class where the method is defined. The “Late Static Binding” feature of PHP binds the call to the class where the method is called. The, function get_called_class() does the same work.

Syntax:

get_called_class()

Parameters:

The function has no parameter.

Return Values:

The function returns the name of the class where the static method is called,

Examples:

Example 1:

<?php
class human {
    static public function eat() {
        print_r(get_called_class());
    }
}

class male extends human{}

echo "The 'eat' method is calling from the parent class: ";
human::eat();
echo "<br />";
echo "The 'eat' method is calling from the child class: ";
male::eat();
?>

Output:

The 'eat' method is calling from the parent class: human
The 'eat' method is calling from the child class: male

Example 2:

<?php
trait Human {
    public static function eat() {
        print_r(get_called_class());
    }
}

class male {use Human;}
class female {use Human;}

echo "The 'eat' method is calling from the class: ";
male::eat();
echo "<br />";
echo "The 'eat' method is calling from the class: ";
female::eat();
?>

Output:

The 'eat' method is calling from the class: male
The 'eat' method is calling from the class: female

PHP Version Support:

PHP 5 >= 5.3.0, PHP 7, PHP 8

Summary: PHP get_called_class() Function

get_called_class() is a class/object type function in PHP. Use this function to get the calling class of a static method.

Reference:

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