PHP实践-什么是闭包?
来源:互联网 发布:c语言入门经典在线阅读 编辑:程序博客网 时间:2024/06/05 00:55
创建闭包
<?php$clousre = function ($name) { return 'Hello ' . $name;};echo $closure('nesfo');我们之所以能调用$closure变量,是因为这个变量的值是一个闭包,而且闭包对象实现了__invoke()魔术方法。只要变量名后有(),PHP就会查找并调用__invoke()方法。通常会把PHP闭包当作函数的回调使用。
array_map(), preg_replace_callback()方法都会用到回调函数,这是使用闭包的最佳时机!
举个例子:
<?php$numbersPlusOne = array_map(function ($number) { return $number + 1;}, [1, 2, 3]);print_r($numbersPlusOne);得到结果:
[2, 3, 4]在闭包出现之前,只能单独创建具名函数,然后使用名称引用那个函数。这么做,代码执行会稍微慢点,而且把回调的实现和使用场景隔离了。
<?phpfunction incrementNum ($number) { return $number + 1;}
$numbersPlusOne = array_map('incrementNum', [1, 2, 3]);print_r($numbersPlusOne);附加状态匿名函数不止可以当回调使用,还可以为PHP附加并封装状态。
PHP中,必须手动调用闭包对象的bindTo()方法或者使用use关键字,才能把状态附加到PHP闭包上。
<?phpfunction enclosePerson ($name) { return function ($doCommand) use ($name) { return $name . ', ' . $doCommand; }}
$clay = enclosePerson('Clay');
echo $clay('get me sweet tea!');得到结果:
"Clay, get me sweet tea!"PHP闭包是对象,每个闭包实例都可以使用$this关键字获取闭包的内部状态。闭包对象的默认状态没什么用,只有__invoke()方法和bindTo方法而已。
我们可以使用bindTo()这个方法,将Closure对象的内部状态绑定到其它对象上。
bindTo()方法的第二个参数:其作用是指定绑定闭包的那个对象所属的PHP类。因此,闭包可以访问绑定闭包的对象中受保护和私有的成员。
PHP框架经常使用bindTo()方法把路由URL映射到匿名回调函数上。这么做可以在这个匿名函数中使用$this关键字引用重要的应用对象。
使用bindTo()方法附加闭包状态<?phpclass 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; }}全选复制放进笔记<?php$app = new App();$app->addRoute('/user/nesfo', function () { $this->responseContentType = 'application/json; charset=utf8'; $this->responseBody = '{"name": "nesfo"}';});$app->dispatch('/user/nesfo');
0 0
- PHP实践-什么是闭包?
- 闭包 什么是闭包
- 什么是闭包
- 什么是闭包
- 什么是 lua 闭包
- 什么是闭包(Closure)?
- 一、什么是闭包?
- 什么是闭包?
- 什么是javascript闭包
- 什么是闭包
- 什么是闭包
- 什么是闭包
- 什么是闭包
- 什么是“闭包”?
- [concept]什么是闭包
- 什么是闭包(Closure)?
- 什么是JS闭包
- 什么是闭包(Closure)?
- 用 Scrapy+Mariadb 实现汉典数据爬虫(一)——开发环境的选择
- 欢迎使用CSDN-markdown编辑器
- 漂亮实用的jQuery倒计时插件特效代码
- Python基础语法
- 软件工具
- PHP实践-什么是闭包?
- Mac brew的安装使用
- JAVA 中IO总结 之前篇阻塞、非阻塞
- Java设计模式透析之 —— 单例(Singleton)
- 替换元素节点
- iOS之self.xxx与_xxx的区别
- 24点游戏
- session机制
- MySql按周,按月,按日分组统计数据