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

php閉包函數(shù)比如你現(xiàn)在就可以這樣使用:

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

感覺(jué)和js是不是一樣的用法了,一些閉包函數(shù)實(shí)例,代碼如下:

  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!”

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

  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將類可以在閉包函數(shù)中使用,代碼如下:

  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. }//開(kāi)源代碼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 

在類之外需要綁定類才能用,綁定可以是類名,也可以是對(duì)象,綁定過(guò)之后可以再次綁定不需要提拱類名或?qū)ο?

轉(zhuǎn)載請(qǐng)注明來(lái)源:php中閉包函數(shù)的用法實(shí)例

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