【问题标题】:Pass anonymous callback function as argument into function?将匿名回调函数作为参数传递给函数?
【发布时间】:2018-05-17 18:14:17
【问题描述】:

我想将一个函数发送到另一个函数中,以便稍后在该函数中执行。这个想法类似于jQuery中的回调成功函数。

想法是这样的:

function my_function($args)
{
    // ...

    // Code that creates the $result variable

    // ..

    // Execute the calback function, how??:
    $args['callback_function']; // Handle the $result
}

$args = array(
    'callback_function' => function($result)
                            {
                                // $result created in my_function()
                            }
);
my_function($args);

【问题讨论】:

    标签: php function callback anonymous-function


    【解决方案1】:

    使用您自己的示例,您可以这样做...

    function my_function($args)
    {
        $res= "your value here";
    
        $args['callback_function']($res); // Handle the $result
    }
    
    $args = array(
        'callback_function' => function($result)
                                {
                                    var_dump($result);
                                }
    );
    my_function($args);
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      $args['callback_function']($result);
      

      或者像这样:

      call_user_func($args['callback_function'], $result);
      

      欲了解更多信息:http://php.net/manual/en/function.call-user-func.php

      示例

      function my_function($args)
      {
          // ...
          // Code that creates the $result variable
          $result = 1;
          // ...
      
          call_user_func($args['callback_function'], $result);
      }
      
      $args = array(
          'callback_function' => function($result) {
              echo ++$result;
          }
      );
      
      my_function($args);
      

      输出

      2
      

      【讨论】: