34

consider this simple scenario:

$this->method($arg1, $arg2);

Solution:

call_user_func_array(array($this,'method'), array($arg1, $arg2));

consider this scenario:

$this->object->method($arg1, $arg2);

Should this solution work?

call_user_func_array(array($this->object,'method'), array($arg1, $arg2));

Or should this work?

    call_user_func_array(array($this, 'object','method'), array($arg1, $arg2));

Edit: Will try/catch works for SOAP exception, triger while using call_user_func?

  try {
    $soap_res = call_user_func_array(array($this->service,'getBanana'), array(0, 10));
} catch (SoapFault $fault) {
    die($fault->faultstring)
} 
2
  • 2
    I reckon this is a question/answer site... but the notion of running both solutions to see which one works never occured to you? Commented Jun 11, 2009 at 13:24
  • It's a test question sponsored by SO, and you have multiple choices. Answers should be in the form of letters A,B or C. Commented Sep 2, 2013 at 5:19

2 Answers 2

76

This should work:

call_user_func_array(array($this->object,'method'), array($arg1, $arg2));

The first argument is a callback type, containing an object reference and a method name.

Sign up to request clarification or add additional context in comments.

2 Comments

To pass the arguments automatically you can use func_get_args(). For example: call_user_func_array(array($this,'method'), func_get_args())
But would that not provoke the first argument (the callback array) to also be passed?
8

Here's a hackish variant, might be useful to someone:

$method_name_as_string = 'method_name';
$this->$method_name_as_string($arg1, $arg2);

This uses the PHP variable-variables. Ugly as hell, but not particularly uglier than the others...

Comments

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.