33

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)
} 
stac
  • 378
  • 1
  • 4
  • 10
  • 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? – Mario Jun 11 '09 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. – Jhourlad Estrella Sep 02 '13 at 05:19

2 Answers2

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.

Greg
  • 316,276
  • 54
  • 369
  • 333
  • 2
    To pass the arguments automatically you can use `func_get_args()`. For example: `call_user_func_array(array($this,'method'), func_get_args())` – Andy Fleming Apr 05 '14 at 23:02
  • But would that not provoke the first argument (the callback array) to also be passed? – algo Nov 13 '22 at 20:43
7

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...

devsnd
  • 7,382
  • 3
  • 42
  • 50