账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    一个让PHP小白百思不得其解的匿名函数及array_reduce的问题
    32
    0

    最近学习PHP,看到了一段代码,其中涉及到了匿名函数以及array_reduce,把代码敲出来用各种方法分析也没想出是怎么调用的,代码如下:

    <?php
    interface Middleware
    {
        public static function handle(Closure $next);
    }
    
    class VerifyCsrfToken implements Middleware
    {
        public static function handle(Closure $next)
        {
            echo "(5)验证Csrf-Token".'<br>';
            $next();
        }
    }
    
    class ShareErrorsFromSession implements Middleware
    {
        public static function handle(Closure $next)
        {
            echo "(4)如果session中有'errors'变量,则共享它".'<br>';
            $next();
        }
    }
    
    class StartSession implements Middleware
    {
        public static function handle(Closure $next)
        {
            echo "(3)开启session,获取数据".'<br>';
            $next();
            echo "(7)保存数据,关闭session".'<br>';
        }
    }
    
    class AddQueuedCookiesToResponse implements Middleware
    {
        public static function handle(Closure $next)
        {
            $next();
            echo "(8)添加下一次请求需要的cookie".'<br>';
        }
    }
    
    class EncryptCookies implements Middleware
    {
        public static function handle(Closure $next)
        {
            echo "(2)对输入请求的cookie进行解密".'<br>';
            $next();
            echo "(9)对输出相应的cookie进行加密".'<br>';
        }
    }
    
    class CheckForMaintenanceMode implements Middleware
    {
        public static function handle(Closure $next)
        {
            echo "(1)确定当前程序是否处于维护状态".'<br>';
            $next();
        }
    }
    
    function getSlice()
    {
        return function($stack, $pipe)
        {
            return function() use ($stack, $pipe)
            {
                return $pipe::handle($stack);
            };
        };
    }
    
    
    function then()
    {
        $pipes = [
            "CheckForMaintenanceMode",
            "EncryptCookies",
            "AddQueuedCookiesToResponse",
            "StartSession",
            "ShareErrorsFromSession",
            "VerifyCsrfToken"
        ];
        
        $firstSlice = function() {
            echo "(6)请求向路由器传递,返回响应.".'<br>';
        };
    
        $pipes = array_reverse($pipes);
        $go = array_reduce($pipes, getSlice(),$firstSlice);
        $go();
    }
    then();
    ?>

    还望有大神能帮忙详解下$go = array_reduce($pipes, getSlice(),$firstSlice);和$go();这两段代码背后的每一步的调用执行流程,以及调用时的参数传递是哪些,如果能用流程图表示就更好啦,谢谢。

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部