Find out which class called a method in another class
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?
Solution 1:
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.
Solution 2:
Here is one liner solution
list(, $caller) = debug_backtrace(false, 2);
As of PHP7 this won't work based on the docs: http://php.net/manual/en/function.list.php as we cannot have empty properties, here is a small update:
list($childClass, $caller) = debug_backtrace(false, 2);