Reading “this” and “use” arguments from a PHP closure

前端 未结 0 1957
刺人心
刺人心 2021-01-13 07:56

When you create a method that returns a closure in PHP:

class ExampleClass {
  public function test() {
    $example = 10;

    return function() use ($examp         


        
相关标签:
回答
  • 2021-01-13 08:48

    It seems you may have overlooked some of the ReflectionFunction methods.

    Take a look at the ReflectionFunction::getClosureThis() method. I tracked it down by looking through the PHP 7 source code by doing a search for the zend_get_closure_this_ptr() which is defined in zend_closures.c.

    The manual currently doesn't have a lot of documentation for this function. I'm using 7.0.9; try running this code based on your example:

    class ExampleClass {
      private $testProperty = 33;
    
      public function test() {
        $example = 10;
    
        return function() use ($example) {
          return $example;
        };
      }
    }
    
    $instance = new ExampleClass();
    $closure = $instance->test();
    
    print_r($closure);
    
    $func = new ReflectionFunction($closure);
    print_r($func->getClosureThis());
    

    You should get output similar to

    Closure Object
    (
        [static] => Array
            (
                [example] => 10
            )
    
        [this] => ExampleClass Object
            (
                [testProperty:ExampleClass:private] => 33
            )
    
    )
    
    ExampleClass Object
    (
        [testProperty:ExampleClass:private] => 33
    )
    

    Regarding the closure static variables, these are returned with ReflectionFunction::getStaticVariables():

    php > var_dump($func->getStaticVariables());
    array(1) {
      ["example"]=>
      int(10)
    }
    
    0 讨论(0)
  • 消灭零回复
提交回复
热议问题