2

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 Answer 1

4

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');
Sign up to request clarification or add additional context in comments.

1 Comment

cool, also if you need to call a class method you can do call_user_func_array(array('className','classMethod'),array('args')) or call_user_func_array(array($object,'classMethod'),array('args'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.