ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-08-28 10:30:28  阅读:658  来源: 互联网

标签:php closures php-7-1


当您创建一个在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)
}

标签:php,closures,php-7-1
来源: https://codeday.me/bug/20190828/1750477.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有