calling method of object of object with call_user_func

孤人 提交于 2019-12-20 09:54:15

问题


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)
} 

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/980708/calling-method-of-object-of-object-with-call-user-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!