PHP - Passing functions with arguments as arguments

社会主义新天地 提交于 2019-12-24 19:33:57

问题


I have several interchangeable functions with different numbers of arguments, for example:

function doSomething1($arg1) {
    …
}

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

I would like to pass a certain number of these functions, complete with arguments, to another handling function, such as:

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

Obviously this syntax is not correct but I think it gets my point across. The handling function would be called something like this:

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

So the question is, how is this actually done?

From my research it sounds like I may be able to "wrap" the "doSomething" function calls in an anonymous function, complete with arguments and pass those "wrapped" functions to the "doTwoThings" function, and since the anonymous function doesn't technically have arguments they could be called in the fashion shown above in the second code snippet. The PHP documentation has me confused and none of the examples I'm finding put everything together. Any help would be greatly appreciated!


回答1:


you could make use of call_user_func_array() which takes a callback (eg a function or class method to run) and the arguments as an array.

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

The func_get_args() means you can feed this funciton and arbitary number of arguments.

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;
}

This would be the same as doing

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


来源:https://stackoverflow.com/questions/48473405/php-passing-functions-with-arguments-as-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!