Get instance of child in parent class

Is there a way to define a child instance in a parent class in PHP? 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 } 

I need to do (if possible) the create InstanceOfChild() ) method, which will tell me an instance of the child class, because many classes can be children from my parent, but I want (let us say) the log that the child calls which methods. Thanks for the help!

+4
source share
3 answers

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

 class Parent1 { public static function whoAmI() { return get_called_class(); } } class Child1 extends Parent1 {} print Child1::whoAmI(); // prints "Child1" 
+8
source
 class Parent { public function InstanceOfChild() { $class = get_class($this); return $class == 'Parent'? // check if base class "This class is not a child": // yes "Child class is instance of " . $class; // its child } } 

Please note that the call:

 $this instanceof Parent 

It will always return true, since the parent and child objects are all instances of the Parent class.

+2
source

You can use get_class . So, you will need to install the following code:

 echo "Child class is instance of ".get_class($childInstance); 

(I'm not a php developer, so the syntax may be wrong)

0
source

Source: https://habr.com/ru/post/1497178/


All Articles