php的闭包

php5.3加入了闭包的新特性,就是匿名函数也叫闭包。

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

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

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

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

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

状态附加 

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

扫描二维码关注公众号,回复: 431111 查看本文章
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');
 

    

猜你喜欢

转载自www.cnblogs.com/hellohell/p/9020029.html
今日推荐