doqdcks3948
2017-09-19 06:33
浏览 257
已采纳

在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

图片转代码服务由CSDN问答提供 功能建议

如何定义和执行数组内的函数

例如我有 数组

  $ a =“a”; 
 $ b =“b”; 
 $ c =“c”;  
 $ array = array(
“a”=> $ a,
“b”=> $ b,
“c”=>函数($ c){
 //做某事\  n返回输出
} 
)
   
 
 

此处的输出应为

  Array 
(
  [a] => a 
 [b] => b 
 [c] =>“c的新值”
 
)
   
 
 <  p>但实际上我得到了 
 
 
  Array 
(
 [a] =&gt; a 
 [b] =&gt; b 
 [c] =&gt  ;闭包对象
(
 [参数] =&gt;数组
(
 [$ c] =&gt; 
)
)
)
 
   
 
  

注意:我可以在此外定义一个函数并调用该函数但我不想这样做

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongyun3897 2017-09-19 06: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条)

相关推荐 更多相似问题