php中閉包函數的用法執行個體

來源:互聯網
上載者:User

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

?>

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.