PHP - 以参数作为参数传递函数

PHP - Passing functions with arguments as arguments

我有几个具有不同数量参数的可互换函数,例如:

function doSomething1($arg1) {
    …
}

function doSomething2($arg1, $arg2) {
    …
}

我想将一定数量的带有参数的这些函数传递给另一个处理函数,例如:

function doTwoThings($thing1, $thing2) {
    $thing1();
    $thing2();
}

显然这种语法不正确,但我认为它表达了我的观点。处理函数将被称为这样的东西:

doTwoThings(‘doSomething1(‘abc’)’, ‘doSomething2(‘abc’, ‘123’));

所以问题是,这实际上是如何完成的?

根据我的研究,听起来我可以 "wrap" 在匿名函数中调用 "doSomething" 函数,完成参数并将这些 "wrapped" 函数传递给 "doTwoThings" 函数,并且由于匿名函数在技术上没有参数,因此可以按照上面第二个代码片段中显示的方式调用它们。 PHP 文档让我感到困惑,none 我发现的示例将所有内容放在一起。任何帮助将不胜感激!

您可以使用 call_user_func_array(),它接受回调(例如 运行 的函数或 class 方法)并将参数作为数组。

http://php.net/manual/en/function.call-user-func-array.php

func_get_args() 意味着您可以为该函数提供任意数量的参数。

http://php.net/manual/en/function.func-get-args.php

domanythings(
  array( 'thingonename', array('thing','one','arguments') ),
  array( 'thingtwoname', array('thing','two','arguments') )
);

funciton domanythings()
{
  $results = array();
  foreach( func_get_args() as $thing )
  {
     // $thing[0] = 'thingonename';
     // $thing[1] = array('thing','one','arguments')
     if( is_array( $thing ) === true and isset( $thing[0] ) and is_callable( $thing[0] ) )
     {
       if( isset( $thing[1] ) and is_array( $thing[1] ) )
       {
         $results[] = call_user_func_array( $thing[0], $thing[1] );
       }
       else
       {
         $results[] = call_user_func( $thing[0] );
       }
     }
     else
     {
       throw new Exception( 'Invalid thing' );
     }
  }
  return $results;
}

这和做的一样

thingonename('thing','one','arguments');
thingtwoname('thing','two','arguments');