PHP - Passing functions with arguments as argument

2019-08-17 00:52发布

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条回答
The star\"
2楼-- · 2019-08-17 01:25

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');
查看更多
登录 后发表回答