0

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?

2
  • 1
    Could you say why you have to avoid passing $this to the method? Commented Nov 15, 2009 at 18:19
  • It just strikes me as unnecessary and it kind of "pollutes" the method signature. If I'm already using $this to create my ReflectionMethod, then I would think that ReflectionMethod would have a handle on that object. Obviously it doesn't for whatever reason. Commented Nov 15, 2009 at 19:03

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.