php的闭包

闭包是指在创建时封装周围状态的函数,即使闭包所在的环境的不存在了,闭包中封装的状态依然存在。

匿名函数其实就是没有名称的函数,匿名函数可以赋值给变量,还能像其他任何PHP函数对象那样传递。不过匿名函数仍然是函数,因此可以调用,还可以传入参数,适合作为函数或方法的回调。

php5.3加入了闭包的新特性,把匿名函数和闭包等同对待,就是匿名函数也叫闭包。

  php的闭包经常用作回调函数,array_map,array_walk,preg_replace_callback函数等

 

 

面向对象对代码的复用是通过继承来实现,面向函数的代码复用是通过函数的嵌套(子函数)实现的 个人认为闭包函数的目的就是实现 函数复用

 

php是面向函数 面向对象的语言,会自动把闭包函数转成内置类 closure的对象实例  closure类有很多功能去给闭包使用

 

 

匿名函数用作动态创建函数,保存到变量

$func = function(){
    exit('hello world!');
}
echo $func();

closure内置类实现了__invoke方法,直接使用变量调用闭包触发__invoke方法

 

状态附加 

   php实现状态附加到闭包函数上使用use关键字和closure的 bindto方法,PHP框架经常使用bindTo()方法把路由URL映射到匿名回调函数上

class App
{
    protected $routes = [];
    protected $responseStatus = '200 OK';
    protected $responseContentType = 'text/html';
    protected $responseBody = 'Hello world';

    public function addRoute($routePath, $routeCallback)
    {
        $this->routes[$routePath] = $routeCallback->bindTo($this, __CLASS__);
    }

    public function dispatch($currentPath)
    {
        foreach ($this->routes as $routePath => $callback) {
            if ($routePath === $currentPath) {
                $callback();
            }
        }
        header('HTTP/1.1' . $this->responseStatus);
        header('Content-type: ' . $this->responseContentType);
        header('Content-length' . mb_strlen($this->responseBody));
        echo $this->responseBody;
    }
}

$app = new App();
$app->addRoute('/user/nesfo', function () {
$this->responseContentType = 'application/json; charset=utf8';
$this->responseBody = '{"name": "nesfo"}';
});
$app->dispatch('/user/nesfo');
 

 

 

 

 

 

 

    

posted @ 2018-05-10 15:47  helloworldlee  阅读(801)  评论(0编辑  收藏  举报