doqdcks3948 2017-09-18 22:33
浏览 261
已采纳

在php数组中定义并执行函数

How To define and execute a function inside array

for example i have a array

    $a="a";
    $b="b";
    $c="c"; 
    $array=array(
         "a"=>$a,
         "b"=>$b,
         "c"=>function($c){
                //do something 
              return output
          }      
    )

here output should be

Array
(
    [a] => a
    [b] => b
    [c] => "new value of c"

)

but actually i am getting

Array
(
    [a] => a
    [b] => b
    [c] => Closure Object
        (
            [parameter] => Array
                (
                    [$c] => 
                )    
        )    
)

NB: i can define a function outside this and call that function inside but i dont want to do that

展开全部

  • 写回答

2条回答 默认 最新

  • dongyun3897 2017-09-18 22:37
    关注

    Since closure is a function and it must be executed in order to get a response. Here's how you can execute and return a response

    $c = 'awesome';
    $array=array(
         "a"=>'test2',
         "b"=> 'test',
         "c"=> call_user_func(function() use ($c) {
                //do something 
              return $c;
          })      
    );
    var_dump($array);//array(3) { ["a"]=> string(5) "test2" ["b"]=> string(4) "test" ["c"]=> string(7) "awesome" }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部