Pavel Štěrba Pavel Štěrba - 3 months ago 24
PHP Question

Get instance of child in parent class

Is there any way how to determine instance of child in parent class in PHP? Let's say we have this code:

class Parent {
public function InstanceOfChild() {
//What to put here to display "Child class is instance of ChildClass123"?
}
}

class ChildClass123 extends Parent {
//Some code here
}


What I need to do (if it's possible) is create method
InstanceOfChild()
which will tell me instance of child class, because a lot of classes can be child of my parent one, but I want to (let's say) log, which child call which methods. Thanks for help!

Answer

There is a function get_called_class() what you are exactly looking for.

class Parent1 {
    public static function whoAmI() {
        return get_called_class();
    }
}

class Child1 extends Parent1 {}

print Child1::whoAmI(); // prints "Child1"