Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out which class called a method in another class

Tags:

php

Is there a way in PHP to find out what object called what method in another object.

Exmaple:

class Foo {   public function __construct()   {     $bar = new Bar();     $bar->test();   } }  class Bar {   public function test()   {   } } $foo = new Foo(); 

Would there be a way for me to find out that the test method was called from the foo object?

like image 967
Botto Avatar asked Jul 31 '09 18:07

Botto


People also ask

How can I get method from another class?

To access the private constructor, we use the method getDeclaredConstructor(). The getDeclaredConstructor() is used to access a parameterless as well as a parametrized constructor of a class. The following example shows the same. // the Vehicle class using the parameterless constructor.

How do you call a method from another class without creating an object?

We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.

How do you call one method from another method in Java?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.


1 Answers

you could use debug_backtrace, a bit like this :
BTW, take a look at the comments on the manual page : there are some useful functions and advices given ;-)

class Foo {   public function __construct()   {     $bar = new Bar();     $bar->test();   } }  class Bar {   public function test()   {       $trace = debug_backtrace();       if (isset($trace[1])) {           // $trace[0] is ourself           // $trace[1] is our caller           // and so on...           var_dump($trace[1]);            echo "called by {$trace[1]['class']} :: {$trace[1]['function']}";        }   } } $foo = new Foo(); 

The var_dump would output :

array   'file' => string '/home/squale/developpement/tests/temp/temp.php' (length=46)   'line' => int 29   'function' => string '__construct' (length=11)   'class' => string 'Foo' (length=3)   'object' =>      object(Foo)[1]   'type' => string '->' (length=2)   'args' =>      array       empty 

and the echo :

called by Foo :: __construct 

But, as nice as it might look like, I am not sure it should be used as a "normal thing" in your application... Seems odd, actually : with a good design, a method should not need to know what called it, in my opinion.

like image 169
Pascal MARTIN Avatar answered Oct 04 '22 11:10

Pascal MARTIN