Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 791
Pavel Štěrba Avatar asked Dec 26 '22 22:12

Pavel Štěrba


1 Answers

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"
like image 150
Shankar Narayana Damodaran Avatar answered Jan 12 '23 19:01

Shankar Narayana Damodaran