duanqi5333 2012-11-22 23:33
浏览 40
已采纳

有没有办法将整个范围传递给函数

Before going into the details of this question, I'd like to point out that I have never seen this done before, and would be rather curious to see if it can actually be done, and if so, how to go about doing it.

I'm currently sitting on a template loader, and to write it, I have chosen to slightly adapt the HAML file format and extend it with a couple of logic operators - loops, mostly. To do so efficiently, I'd need to pass a list of parameters to the template parser...and I'd prefer to avoid this if possible. While brainstorming for alternatives, the idea came around that maybe, just maybe, it would be possible to reference the scope in which the function was called.

Currently, I'm calling the template parser for a file as follows. Suppose test() is a route.

function test() {
   $q = $UserModel->tether($userID)->fetchPermissions();
   Util::Templating()->parse("file.haml");
}

What I'm trying to avoid is being able to access $q without passing a massively long array as second parameter. My original thought was that there might be a way for parse() to inherit the scope in which it was originally called (here, inside test) rather than having its own. Is there a way to manage this, and if so, how efficient is it?

  • 写回答

2条回答 默认 最新

  • dq23171 2012-11-22 23:47
    关注

    Includes the superglobals as well:

    $a = 'Hello World';
    $b = range('A','Z');
    
    $scopeVars = get_defined_vars();
    
    var_dump($scopeVars);
    test($scopeVars);
    
    
    function test($scopeVars) {
        extract($scopeVars);
    
        echo '$a = '; var_dump($a);
        echo '$b = '; var_dump($b);
    }
    

    EDIT

    Just as an experiment, to eliminate the superglobals:

    $a = 'Hello World';
    $b = range('A','Z');
    
    $scopeVars = get_user_defined_vars(get_defined_vars());
    
    test($scopeVars);
    
    
    function test($scopeVars) {
        extract($scopeVars);
    
        echo '$a = '; var_dump($a);
        echo '$b = '; var_dump($b);
    }
    
    function get_user_defined_vars($vars) {
        return array_diff_key(
            $vars, 
            array_flip(
                array('_SERVER','_GET', '_POST', '_REQUEST', '_FILES', '_COOKIE', '_ENV')
            )
        );
    }
    

    But removing the superglobals does seem to make it a bit slower

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊