dqg95034 2017-07-14 15:21
浏览 96
已采纳

我可以使用PHP匿名函数作为参数,而无需将函数赋值给变量吗?

Does PHP allow the use of an anonymous function as one of the arguments during concatenation?

If so, what is the proper syntax?

For example, here's an example of what I want to get to work:

$final_text = $some_initial_string . function ($array_of_strings)
{
    $out = '';
    foreach ($array_of_strings as $this_particular_string)
    {
        $out .= $this_particular_string;
    }
    return $out;
};
  • 写回答

1条回答 默认 最新

  • douzi8112 2017-07-14 15:29
    关注

    Note: the below is expected to work for PHP Version 7.x but does not work on PHP Version 5.6 (For 5.6, first assign the anonymous function to a variable)

    /*
     * Strings before & after
     */
    $table_heading_text = "HEADING";
    $table_bottom_text = "BOTTOM";
    
    /*
     * Use the function this way
     */
    echo $table_heading_text . (function (array $array_of_strings)
    {
        $out = '';
        foreach ($array_of_strings as $this_particular_string)
        {
            $out .= $this_particular_string;
        }
        return $out;
    })(array(
        "hi",
        "mom"
    )) . $table_bottom_text;
    

    In short ...

    1. function must return some value that can be converted to text
    2. function definition must be enclosed in parenthesis ( ... )
    3. Don't forget to have calling arguments after the function definition

    Examples:

    echo "BEFORE" . (function ($x){return $x;})(" - MIDDLE - ") . "AFTER";
    echo "BEFORE" . (function (){return " - MIDDLE - ";})() . "AFTER";
    

    Also, using implode() may be better for this particular task.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘