dphphvs496524 2012-06-26 22:42
浏览 36
已采纳

php闭包实例5.3

This a little hard for me to explain, but I'll try my best. I'm trying to find the best way to create an instance of a closure. Below is an example of how I am creating and accessing the closure:

$myvar->parse('var1, var2', function () {
  //my code
});

I then loop through the strings by exploding the comma and put it into an array like so.

$array = array();
$array['var1'] = closure();
$array['var2'] = closure();

Later on in my code I use call_user_func to execute the function.

Now, the issue I'm having is that when I access $array['var1'] it calls the closure without any problem.

But when I access $array['var2'] it does nothing. I've been looking at diverse websites for a while without much luck. Do I need to use pointers (tried without success) or create a new instance of it somehow?

I currently only have access to php 5.3 on my server, so I can't use any of the awesome stuff in 5.4 :(

I'd really appreciate any feedback and advice you may have.

  • 写回答

2条回答 默认 最新

  • dras2334 2012-06-26 22:46
    关注

    Yes your question isn't clear. You knew it so I wonder why you didn't explained better.

    Anyway if you need to run a closure stored inside $array['var2'] you have to specifically put in your code something like this:

    $array['var2'] = function(){
    //> Code
    };
    

    That's the only way

    By guessing at your code, your function parse should like:

    function parse($keys,$func) {
     $array = array();
     foreach(explode(',',$keys) as $v) {
       $array[trim($v)] = $func;  //> trim important here!
     }
    }
    

    Most likely you have forgot to trim($v)

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

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?