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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With