Pavel Štěrba Pavel Štěrba - 1 year ago 143
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
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 Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download