php中Closure::bind用法(手冊記錄)

來源:互聯網
上載者:User

標籤:

  手冊中 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 HackThursday30 {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時的問題,以及解決方案這篇一起看加深理解.

 

php中Closure::bind用法(手冊記錄)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.