Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child class name php from static function

Tags:

oop

php

In php I have a ROOT class from which all other classes inherit.

abstract class ROOT{
    public static function getClass(){

    }
}

I want that function to return the class(name) of the object which inherits from this class. So if I create an object Tree (extends ROOT) and call getClass on it it should say "Tree"

The function get_class() only works on objects, so can't be used inside a static function. Is there any way to accomplish this?

like image 459
Max Snijders Avatar asked May 28 '26 05:05

Max Snijders


2 Answers

Instead of get_class(), use get_called_class().

like image 110
SDC Avatar answered May 30 '26 19:05

SDC


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

abstract class ROOT {
    public static function getClass() {
        return get_called_class();
    }
}
class Tree extends ROOT {
}

$Tree = new Tree();
echo $Tree->getClass();  // Outputs "Tree"
like image 38
Cryszon Avatar answered May 30 '26 20:05

Cryszon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!