国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

php中閉包函數的用法實例

2024-09-04 11:48:41
字體:
來源:轉載
供稿:網友

閉包函數是在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. }//開源代碼Vevb.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 

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 华阴市| 文山县| 东港市| 冀州市| 凤翔县| 泰州市| 丽江市| 长子县| 南京市| 会同县| 朝阳区| 崇礼县| 苍梧县| 临漳县| 宁都县| 南宁市| 西乌珠穆沁旗| 岑巩县| 延川县| 衡山县| 新泰市| 长汀县| 台州市| 南城县| 怀仁县| 新津县| 江门市| 新干县| 西安市| 大余县| 色达县| 油尖旺区| 浏阳市| 鹰潭市| 定南县| 榆树市| 白沙| 松潘县| 西丰县| 黄浦区| 泸西县|