閉包函數是在PHP5.3版本才引入的了,閉包函數也就是匿名函數函數了,這個與js中的匿名函數很像了,下面我們來看看php匿名函數吧.

php閉包函數比如你現在就可以這樣使用:

$closure = function($param) { echo $param; };

感覺和js是不是一樣的用法了,一些閉包函數實例,代碼如下:

  1. function test(){ 
  2. $test=''
  3. $test=function ($str){ 
  4. echo 'test'
  5. return $str
  6. }; 
  7. timeout('Y-m-d H:i:s',function ($time){ 
  8. //$this->date=time(); 
  9. return $time-24*60*60; 
  10. }); 
  11.  
  12. var_dump($test(‘hello word!’)); 
  13.  
  14. function timeout($format,$time){ 
  15. echo date($format,$time(time())); 
  16. test(); 

上例輸出:2013-11-19 16:24:56teststring(11) “hello word!”

這樣子參數便可以用函數了,條件是,php3.0以后php 4.0以后閉包函數支持$this用法,閉包函數通常被用在preg_match等有callback的函數,代碼如下:

  1. <?php 
  2. class A { 
  3. private static $sfoo = 1; 
  4. private $ifoo = 2; 
  5. $cl1 = static function() { 
  6. return A::$sfoo
  7. }; 
  8. $cl2 = function() { 
  9. return $this->ifoo; 
  10. }; 
  11.  
  12. $bcl1 = Closure::bind($cl1, null, ‘A’); 
  13. $bcl2 = Closure::bind($cl2new A(), ‘A’); 
  14. echo $bcl1(), “n”; 
  15. echo $bcl2(), “n”; 
  16. ?> 
  17. //輸出 

bind將類可以在閉包函數中使用,代碼如下:

  1. <?php 
  2. class A1 { 
  3. function __construct($val) { 
  4. $this->val = $val; 
  5. function getClosure() { 
  6. //returns closure bound to this object and scope 
  7. return function() { return $this->val; }; 
  8. }//開源代碼phpfensi.com 
  9.  
  10. $ob1 = new A1(1); 
  11. $ob2 = new A1(2); 
  12.  
  13. $cl = $ob1->getClosure(); 
  14. echo $cl(), “n”; 
  15. $cl = $cl->bindTo($ob2); 
  16. echo $cl(), “n”; 
  17. ?> 
  18. //以上例程的輸出類似于: 

bindto在類里可以再次綁定類,代碼如下:

  1. $fn = function(){ 
  2. return ++$this->foo; // increase the value 
  3. }; 
  4.  
  5. class Bar{ 
  6. private $foo = 1; // initial value 
  7.  
  8. $bar = new Bar(); 
  9.  
  10. $fn1 = $fn->bindTo($bar, ‘Bar’); // specify class name 
  11. $fn2 = $fn->bindTo($bar$bar); // or object 
  12. $fn3 = $fn2->bindTo($bar); // or object 
  13.  
  14. echo $fn1(); // 2 
  15. echo $fn2(); // 3 
  16. echo $fn3(); // 4 

在類之外需要綁定類才能用,綁定可以是類名,也可以是對象,綁定過之后可以再次綁定不需要提拱類名或對象.

轉載請注明來源:php中閉包函數的用法實例

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網站,并且能夠搭建符合百度排名規(guī)范的網站基底,使您的網站無需額外費用,即可穩(wěn)步提升排名至首頁。歡迎體驗最佳的哈爾濱網站建設。