php中Closure::bind用法(手册记录)

  手册中 Closure::bind — 复制一个闭包,绑定指定的$this对象和类作用域。

  具体参数可以看手册,这里记录下这个方法的实际用处.

 1 <?php
 2 
 3 trait MetaTrait
 4 {
 5     private $methods = [];
 6 
 7     public function addMethod($methodName,$methodCallable)
 8     {
 9         if (!is_callable($methodCallable))
10             throw new InvalidArgumentException('Second param must be callable');
11 
12         //改变作用域到 get_called_class 的对象
13         $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_called_class());
14 
15     }
16 
17     public function __call($methodName, array $args)
18     {
19         if (isset($this->methods[$methodName])){
20             return call_user_func_array($this->methods[$methodName],$args);
21         }
22 
23         throw new RuntimeException('There is no method with the given name to call');
24 
25     }
26 
27 }
28 
29 class HackThursday
30 {
31     use MetaTrait;
32 
33     private $dayOfWeek = 'Thursday';
34 }
35 
36 
37 $test = new HackThursday();
38 $test->addMethod('when',function(){
39     return $this->dayOfWeek;
40 });
41 
42 echo $test->when(); //Thursday

  其实这个方法就是以前说过的 Closure::bindTo() 的静态版本, 和PHP 使用reflection时的问题,以及解决方案这篇一起看加深理解.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值