php閉包函數比如你現在就可以這樣使用:
代碼如下 |
複製代碼 |
$closure = function($param) { echo $param; }; |
感覺和js是不是一樣的用法了.
一些閉包函數執行個體
代碼如下 |
複製代碼 |
function test(){ $test=''; $test=function ($str){ echo 'test'; return $str; }; timeout('Y-m-d H:i:s',function ($time){ //$this->date=time(); return $time-24*60*60; });
var_dump($test(‘hello word!’)); } function timeout($format,$time){ echo date($format,$time(time())); } test(); ?> |
上例輸出
2013-11-19 16:24:56teststring(11) “hello word!”
這樣子參數便可以用函數了。
條件是,php3.0以後php 4.0以後閉包函數支援$this用法
閉包函數通常被用在preg_match等有callback的函數
代碼如下 |
複製代碼 |
class A { private static $sfoo = 1; private $ifoo = 2; } $cl1 = static function() { return A::$sfoo; }; $cl2 = function() { return $this->ifoo; }; $bcl1 = Closure::bind($cl1, null, ‘A’); $bcl2 = Closure::bind($cl2, new A(), ‘A’); echo $bcl1(), “n”; echo $bcl2(), “n”; ?> |
輸出
1
2
bind將類可以在閉包函數中使用
代碼如下 |
複製代碼 |
class A1 { function __construct($val) { $this->val = $val; } function getClosure() { //returns closure bound to this object and scope return function() { return $this->val; }; } }
$ob1 = new A1(1); $ob2 = new A1(2); $cl = $ob1->getClosure(); echo $cl(), “n”; $cl = $cl->bindTo($ob2); echo $cl(), “n”; ?> |
以上常式的輸出類似於:
1
2
bindto在類裡可以再次綁定類
代碼如下 |
複製代碼 |
$fn = function(){ return ++$this->foo; // increase the value }; class Bar{ private $foo = 1; // initial value } $bar = new Bar(); $fn1 = $fn->bindTo($bar, ‘Bar’); // specify class name $fn2 = $fn->bindTo($bar, $bar); // or object $fn3 = $fn2->bindTo($bar); // or object echo $fn1(); // 2 echo $fn2(); // 3 echo $fn3(); // 4 ?> |
在類之外需要綁定類才能用,綁定可以是類名,也可以是對象,綁定過之後可以再次綁定不需要提拱類名或對象