public function on($event, $callback) {
if (!isset($this-listeners[$event])) {
$this-listeners[$event] = [];
}
$this-listeners[$event][] = $callback;
}
public function emit($event, $data = null) {
if (isset($this-listeners[$event])) {
foreach ($this-listeners[$event] as $callback) {
$callback($data);
}
}
}
}
public function bind($key, $resolver) {
$this-bindings[$key] = $resolver;
}
public function resolve($key) {
if (isset($this-bindings[$key])) {
return call_user_func($this-bindings[$key]);
}
throw new Exception(Binding not found: $key);
}
}
// 二次开发:注册一个数据库连接
$container = new Container();
$container-bind('db', function() {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
});
$db = $container-resolve('db');
✅ 适合构建模块化、可插拔的框架或应用。
4、闭包捕获外部变量(作用域控制)
匿名函数可以“捕获”外部变量,这是其强大之处:
php
function makeCounter($start = 0) {
$count = $start;
return function() use (&$count) {
return $count++;
};
}