dppfxf909679 2016-01-01 18:30
浏览 26
已采纳

在PHP中,如何在另一个函数中使用函数作为参数?

I know that this question may have been asked before, but I don't quite understand the whole concept of anonymous functions (closures), and how they would apply specifically to my situation. NB: I know it is quite silly to have all these simple functions, but my task requirements say that I should have all these functions :/ . I have several functions. In the function below, the parameters $action1 and $action2 will be both replaced by functions:

function dothis($num1, $num2, $action1, $action2)
{
    $result = $num1 + $num2;
    if ($result > 52){
        //do $action1 which is a function
    } else {
        //do $action2 which is another function
    }

    return $result;
}

The function dothis will be called in another function called add. Here is the add function:

function add($action1,$action2) 
{
     $answer = dothis(42, 34, $action1, $action2);
     echo $answer;
}

$action1 and $action2 in the add function are essentially the same as the $action1 and $action2 in the dothis function. Do they need to have different names now even though they are the same things?

Now, the add function will be called in the main function, where the parameters $action1 and $action2, will be replaced by the actual functions that they correspond to:

function main() 
{
    add($fun1,$fun2);
    echo 'Arithmetic complete';
}

This is the code for $fun1 and $fun2:

$fun1 = function () {
    echo 'Wow! The answer is greater than 52.';
};

$fun2 = function () {
    echo 'Oh no! The answer is less than 52.'; 
};

What should I do, and what do I need to change? I really appreciate any help. Thanks in advance!

  • 写回答

2条回答 默认 最新

  • dongqidi2799 2016-01-01 18:53
    关注

    See the PHP documentation on Variable Functions

    You call a function by putting () after it (with arguments inside the parentheses if necessary).

    function dothis($num1,$num2,$action1,$action2){
        $result = $num1 + $num2;
        if ($result > 52){
            $action1();
        }
        else{
            $action2();
        }
        return $result;
    }
    

    For this syntax to work with anonymous functions, you have to turn off eAccelerator. See Anonymous functions does not work: Function name must be a string

    If you can't use anonymous functions, you'll need to use named functions.

    function fun1 () {
        echo 'Wow! The answer is greater than 52.';
    }
    $fun1 = 'fun1';
    
    function fun2() {
        echo 'Oh no! The answer is less than 52.';
    }
    $fun2 = 'fun2';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置