Is there a way in PHP to find out what object called what method in another object.
Exmaple:
class Foo
{
public function __construct()
{
$bar
You could also have the calling object pass itself as an argument
e.g.
class Foo
{
public function __construct()
{
$bar = new Bar();
$bar->test($this);
}
}
class Bar
{
public function test()
{
}
}
$foo = new Foo();
I got this idea from the book "Design Patterns: elements of reusable object-oriented software" by Erich Gamma, et al, on page 278 in the discussion on the "Mediator" structural pattern.
The point of the pattern is to reduce the number of many-to-many connections between a bunch of objects/classes. You create a mediator class that all those classes treat as a hub. That way the classes don't need to know about each other. The mediator handles the interactions. For the mediator to be informed of changes in the classes it tracks, they can pass themselves as arguments, or the mediator can be implemented using the "Observer" pattern.
2018 EDIT:
I sometimes use interfaces with the above code, like this:
interface someInterface // many classes may implement this interface
{
public function giveMeBar();
}
class Foo implements someInterface
{
public function __construct()
{
$bar = new Bar();
$bar->test($this);
}
public function giveMeBar() {
return 'Bar';
}
}
class Bar
{
public function test(someInterface $a)
{
echo $a->giveMeBar();
}
}
$foo = new Foo(); // prints "Bar"
This function does the job without debug_backtrace :
/*
usage :
some code...
getRealCallClass(__FUNCTION__);
some code...
*/
function getRealCallClass($functionName) //Parameter value must always be __FUNCTION__
{
try
{
throw new exception();
}
catch(exception $e)
{
$trace = $e->getTrace();
$bInfunction = false;
foreach($trace as $trace_piece)
{
if ($trace_piece['function'] == $functionName)
{
if (!$bInfunction)
$bInfunction = true;
}
elseif($bInfunction) //found !!!
{
return $trace_piece['class'];
}
}
}
}