dongsong1911 2015-11-13 21:54
浏览 29
已采纳

数组项是一个闭包对象,我可以将其返回值作为相同的数组项吗?

I have this array:

$people = array( 
   'kids' => 100, 
   'adults' => function() {
       return 1000
   }
);

If I do print_r($people) I get:

Array ([kids] => 100, [adults] => Closure Object() )

How do I get - at that same array position - the return value of the closure object instead of the Closure Object itself?

Is this possible in PHP ?

  • 写回答

1条回答 默认 最新

  • dou44364983 2015-11-13 21:59
    关注
    $myFunction = function() { return 1000; };
    $people = array( 'kids' => 100, 'adults' => $myFunction());
    

    If you try to do it inline like this:

    $people = array( 'kids' => 100, 'adults' => function() { return 1000; }());
    

    You will get a parse error:

    PHP Parse error: syntax error, unexpected '(', expecting ')'

    If you must do it on one line, you can use call_user_func:

    $people = array( 
        'kids' => 100, 
        'adults' => call_user_func(function(){ return 1000; })
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile