分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

php的闭包

发布时间:2023-09-06 01:53责任编辑:赖小花关键词:闭包

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

匿名函数其实就是没有名称的函数,匿名函数可以赋值给变量,还能像其他任何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‘);
 

    

php的闭包

原文地址:https://www.cnblogs.com/hellohell/p/9020029.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved