Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling method of object of object with call_user_func

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) }  
like image 645
stac Avatar asked Jun 11 '09 12:06

stac


People also ask

Why use call_ user_ func?

The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions.

What is call_ user_ func_ array in PHP?

The call_user_func_array() function is a special way to call an existing PHP function. It takes a function to call as its first parameter, then takes an array of parameters as its second parameter.

How to call function in array PHP?

Instead of executing the function in an array you can directly assign to some variable and call the function and pass the arguments, then you can use that assigned variable inside your array.


2 Answers

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.

like image 134
Greg Avatar answered Sep 30 '22 15:09

Greg


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

like image 22
devsnd Avatar answered Sep 30 '22 16:09

devsnd