首页 > php函数 > php中闭包函数的用法实例

php中闭包函数的用法实例

闭包函数是在PHP5.3版本才引入的了,闭包函数也就是匿名函数函数了,这个与js中的匿名函数很像了,下面我们来看看php匿名函数吧。

php闭包函数比如你现在就可以这样使用:

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

感觉和js是不是一样的用法了.

一些闭包函数实例

<?php
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的函数

<?php
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将类可以在闭包函数中使用

<?php
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在类里可以再次绑定类

<?php
$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
?>

在类之外需要绑定类才能用,绑定可以是类名,也可以是对象,绑定过之后可以再次绑定不需要提拱类名或对象


本文地址:http://www.phprm.com/function/55586.html

转载随意,但请附上文章地址:-)

标签:preg_match

相关文章

发表留言