当前位置:网站首页>PHP闭包函数 bingTo的使用
PHP闭包函数 bingTo的使用
2022-08-08 23:20:00 【张康佳】
前言
提示:关于闭包函数附加状态的使用。
一、闭包函数是什么?
说明:闭包函数其实就是没有名称的函数。特性:闭包函数是创建时封装周围状态的函数。即便闭包所在的环境不存在了,闭包中封装的状态依然存在。
建议先看一下官方手册:[PHP.net传送门](https://www.php.net/manual/zh/functions.anonymous.php)
二、高级玩法-bingTo()
基本用法见手册,就不展示了,这里直接上一个高级玩法
1.bingTo()说明
使用 bingTo() 方法可以把 Closure 对象的内部状态绑定到其他对象上。简而言之,就是绑定闭包所属的PHP类,这样闭包就可以在其他地方访问绑定闭包的对象中受保护和私有的成员变量。
2.示例 (来源 《Moderm PHP》)
先书写 PHP 类:
class App {
protected $routes = [];
protected $responseStatus = '200 OK';
protected $responseContentType = 'text/html';
protected $responseBody = 'Hello World';
public function addRoute($path, $callback) {
//这里将用户传递的 匿名函数 绑定了 APP
$this->routes[$path] = $callback->bindTo($this, __CLASS__);
}
public function dispatch($path) {
foreach ($this->routes as $routePath => $callback) {
if( $routePath === $path) {
$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('users/josh', function(){
//由于上方绑定了 App, 所以这里可以放到到 APP 中受保护的文件
$this->responseContentType = 'application/json;charset=utf8';
$this->responseBody = '{"name":"Josh"}';
})
$app->dispatch('users/josh');
边栏推荐
- Hi3516 使用 wifi模块
- [Tensorflow2] Some interface changes of tensorflow1.x-tensorflow2.x
- 每日一R「01」跟着大佬学 Rust
- Oracle 锁表,如何解锁
- (2022牛客多校五)C-Bit Transmission(思维)
- ViewOverlay与ViewGroupOverlay
- wps a列不见了怎么办?wps a列不见了的解决方法
- (2022牛客多校四)K-NIO‘s Sword(思维)
- (2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
- Button Wizard Delete File Command
猜你喜欢

A preliminary study on the use of ndk and JNI

(2022牛客多校四)A-Task Computing (排序+动态规划)

wps表格怎么调整表格大小?wps表格调整表格大小的方法

【latex异常与错误】There were undefined references.Reference `xxx‘ on page x undefined.参考引用公式编号时发生错误
![微信小程序错误 undefined Expecting ‘STRING‘,‘NUMBER‘,‘NULL‘,‘TRUE‘,‘FALSE‘,‘{‘,‘[‘, got ]解决方案](/img/31/a9b0c31f648d41e300949ac43c5cab.png)
微信小程序错误 undefined Expecting ‘STRING‘,‘NUMBER‘,‘NULL‘,‘TRUE‘,‘FALSE‘,‘{‘,‘[‘, got ]解决方案

Introduction to Qt (5) - file operation, hotkey and mouse reading (implementation of txt window)

(2022牛客多校五)H-Cutting Papers(签到)

用工具实现 Mock API 的整个流程

【Bug解决】ValueError: Object arrays cannot be loaded when allow_pickle=False

(nowcoder22529C)dinner(容斥原理+排列组合)
随机推荐
弹出PopupWindow后让背景变暗的方法
2022牛客多校六 A-Array(构造+哈夫曼)
抽象内部类
深拷贝与浅拷贝
Kubernetes资源编排系列之四: CRD+Operator篇
RecyclerView的多选模式
(2022牛客多校五)D-Birds in the tree(树形DP)
Hi3516 use wifi module
(2022杭电多校三)1009.Package Delivery(贪心)
从洞察到决策,一文解读标签画像体系建设方法论丨DTVision分析洞察篇
ndk和JNI的使用初探
Kubernetes 企业如何落地
线性筛求积性函数
(2022牛客多校四)H-Wall Builder II(思维)
第二课:概率论
如何搭建一套自己公司的知识共享平台
Share | design based on MCU P0 mouth to drive the LED flashing
wps表格分两页断开怎么办?wps表格分两页断开的解决方法
flutter 基本类写法
wps表格怎么筛选出需要的内容?wps表格筛选出需要的内容的方法