PHP 怎么获取闭包函数的static、this和parameter属性值

闭包函数,又称作匿名函数。PHP手册中又解释Closure是用于代表匿名函数的类.。
匿名函数,顾名思义是没有名字的函数。其中,匿名函数也叫闭包函数。

<?php
$closure = function(){echo "hello";}; // 首先我们创建一个匿名函数
var_dump($closure); // 输出object(Closure)#1 (0) { } 
$closure(); // 输出hello

由此我们可以看出创建一个匿名函数,实际上是创建了一个Closure类的对象。
所以closure其实是一个伪装成函数的对象。

我们创建一个参数完整的闭包函数,看看closure里面到底有什么。

//首先创建了一个Apple类
Class Apple{
    public static $name = "apple";
    public $color ="red";
    private $money = 10;
    public function getClosure(){
        $ex1 = self::$name;
        $ex2 = $this->money;
        return function($name) use($ex1,$ex2){
            echo $name."买了".$ex1."花了".$ex2;
        };
    }
}
$apple = new Apple();
$c =$apple->getClosure();
var_dump($c); //输出闭包。

//输出格式如下
object(Closure)#2 (3) {
  ["static"]=>
  array(2) {
    ["ex1"]=>
    string(5) "apple"
    ["ex2"]=>
    int(10)
  }
  ["this"]=>
  object(Apple)#1 (2) {
    ["color"]=>
    string(3) "red"
    ["money":"Apple":private]=>
    int(10)
  }
  ["parameter"]=>
  array(1) {
    ["$name"]=>
    string(10) "
<required>"
  }
}

由上述代码可以看出一个参数齐全的闭包自动添加了三个属性,分别是:static,this和parameter。
闭包引用的外部变量参数自动给了static属性。
同时,闭包所属的对象也就是apple对象自动给了一个this属性。
闭包所需要输入的参数自动给了parameter属性,并且提示需要等待输入。

那么怎么获取闭包函数的属性值呢?
举例说明:

如果要获取parameter参数

$reflection = new ReflectionFunction($c);
$arguments  = $reflection->getParameters();

注意:获取不同的参数就是$reflection后面的方法不一样

参考链接:

https://stackoverflow.com/questions/19198804/deducing-php-closure-parameters

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值