English 中文(简体)
Using ReflectionMethod::invoke in a context when original object is not in scope
原标题:

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?

问题回答

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();




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签