从PHP闭包中读取“this”和“use”参数

 

当您创建一个在PHP中返回闭包的方法时:

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

    return function() use ($example) {
      return $example;
    };
  }
}

print_r的结果包含this(其方法创建闭包的类)和static,它看起来是闭包的use()语句中绑定的值:

$instance = new ExampleClass();
$closure = $instance->test();

print_r($closure);

生产:

Closure Object (
    [static] => Array (
        [example] => 10
    )
    [this] => ExampleClass Object()
)

但是,我不能为我的生活弄清楚如何捕捉这些价值观.如果没有收到以下信息,则无法使用任何形式的财产访问者(例如$closure-> static或$closure-> {‘static’}):

 

PHP Fatal error: Uncaught Error: Closure object cannot have properties in XYZ.

数组访问符号显然也不起作用:

 

PHP Fatal error: Uncaught Error: Cannot use object of type Closure as array in XYZ.

JSON编码对象,除了这使得值无用是他们的对象,提供一个空的JSON对象{}并且使用ReflectionFunction类不提供对这些项的访问.

closure文档根本没有提供任何访问这些值的方法.

除了输出缓冲和解析print_r或类似的东西之外,我实际上无法看到获取这些值的方法.

我错过了一些明显的东西吗

 

Note: The use-case is for implementing memoization and these values would be extremely beneficial in identifying whether or not the call matched a previous cached call.

解决方法:

看来你可能忽略了一些ReflectionFunction方法.

看看ReflectionFunction::getClosureThis()方法.我通过搜索0700中定义的zend_get_closure_this_ptr()来查看PHP 7源代码来跟踪它.

该手册目前没有很多关于此功能的文档.我使用的是7.0.9;尝试根据您的示例运行此代码:

 

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

你应该得到类似的输出

 

Closure Object
(
    [static] => Array
        (
            [example] => 10
        )

    [this] => ExampleClass Object
        (
            [testProperty:ExampleClass:private] => 33
        )

)

ExampleClass Object
(
    [testProperty:ExampleClass:private] => 33
)

关于闭包静态变量,它们与ReflectionFunction :: getStaticVariables()一起返回:

 

php > var_dump($func->getStaticVariables());
array(1) {
  ["example"]=>
  int(10)
}


来源: https://codeday.me/bug/20190828/1750477.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值