mercredi 23 novembre 2016

How can I invoke a ReflectionFunction wrapping a closure that utilizes $this?

This is easiest to explain with an example:

class Example {
    private $x;
    public $f;

    public function __construct() {
        $this->x = 10;
        $this->f = function() {
            return $this->x;
        };
    }
}

$ex = new Example();
$f = new ReflectionFunction($ex->f);
echo $f->invoke().PHP_EOL;

Running this results in an error:

PHP Fatal error: Uncaught Error: Using $this when not in object context

That's because I've used $this in the closure, so it's really more like a ReflectionMethod, but ReflectionMethod doesn't seem to want to take a closure as an argument, so I'm not really sure what I can do.

How can I invoke $ex->f using reflection?





Aucun commentaire:

Enregistrer un commentaire