tags:

views:

44

answers:

1

I'm trying to do something like this:

class A {
   public function foo() {
      $b = new B;
      $b->invokeMethodFromAnotherObject(new ReflectionMethod($this, 'bar'));
   }
   public function bar() {

   }
}

class B {
   public function invokeMethodFromAnotherObject(ReflectionMethod $method) {
        $method->invoke(?);
   }
}

But there's no apparent way to "suck" $this back out of the reflection method, and I don't have a reference to the object in question. Is there a way I could do this without passing $this into B::invokeMethodFromAnotherObject?

+1  A: 

Reflection methods have no clue about objects. Even if you pass $this to the "new ReflectionMethod", the resulting object only stores a class reference. What you want here is actually a closure (php 5.3) or the good old array($this, 'bar') + call_user_func in the callback.

class A {
  function foo() {
    $b = new B;
    $that = $this;
    $b->invoke(function() use($that) { $that->bar(); });
 }

 function bar() {
     echo "hi";
 }
}

class B {
 function invoke($func) {
   $func();
 }
}

$a = new A;
$a->foo();
stereofrog
What I meant was passing $this as a parameter of B::invokeMethodFromAnotherObject and then doing $method->invoke($object, 'bar'). This works, but it strikes me that ThereMustBeABetterWay.When you mentioned using a Closure, what exactly did you have in mind?
blockhead
"closure" is a familiar term for a function bound to some context (this is basically what you're after)closures in php 5.3: http://www.php.net/manual/en/functions.anonymous.php
stereofrog
I know what a closure is, I'm just not sure exactly how exactly you're suggesting to implement it to solve my particular problem. If you could post an example so that I could understand that would be good.
blockhead
code example added
stereofrog
I see what you mean, but in my particular instance I need to be working off of ReflectionMethod. I'm doing things in the other class like reading off the parameters for the action and invoking them with filled in values.
blockhead