PHP closure

来源:互联网 发布:淘宝收藏的店铺在哪里 编辑:程序博客网 时间:2024/06/09 23:49

(PHP 5 >= 5.3.0, PHP 7)  Class used to represent anonymous functions.


function createGreeter($who) {
              return function() use ($who) {
                  echo "Hello $who";
              };
}

$greeter = createGreeter("World");
$greeter(); // Hello World

===============================

<?phpclass A {    public $base = 100;}class B {    private $base = 1000;}$f = function () {    return $this->base + 3;};$a = Closure::bind($f, new A);print_r($a());echo PHP_EOL;$b = Closure::bind($f, new B , 'B');print_r($b());echo PHP_EOL;

上面的例子中,f这个匿名函数中莫名奇妙的有个f这个匿名函数中莫名奇妙的有个this,这个this关键词就是说明这个匿名函数是需要绑定在类中的。






0 0
原创粉丝点击