贴一段在知乎上看到的代码, 想了很久还是没想通, 求大神通俗讲解:
<?php
namespace App;
interface Middleware
{
public function handle($next);
}
class Session implements Middleware
{
public function handle($next)
{
echo "<br/>Session Start<br/>";
$next();
echo "<br/>Session End<br/>";
}
}
class Mysql implements Middleware
{
public function handle($next)
{
echo "<br/>Mysql Start<br/>";
$next();
echo "<br/>Mysql end<br/>";
}
}
function run($next, $step)
{
return function () use ($next, $step) {
call_user_func_array([new $step, 'handle'], [$next]);
};
}
$class = [Session::class, Mysql::class];
$callback = array_reduce($class, 'App\run', function () {});
$callback();
运行结果
Mysql Start
Session Start
Session End
Mysql end
请输入代码