php 使用 call_user_func 调用对象对象的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/980708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:33:08  来源:igfitidea点击:

calling method of object of object with call_user_func

phpfunctiondynamic

提问by stac

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/catch 是否适用于 SOAP 异常,在使用 call_user_func 时触发?

  try {
    $soap_res = call_user_func_array(array($this->service,'getBanana'), array(0, 10));
} catch (SoapFault $fault) {
    die($fault->faultstring)
} 

回答by Greg

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.

第一个参数是一个回调类型,包含一个对象引用和一个方法名称。

回答by devsnd

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

这是一个hackish变体,可能对某人有用:

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

这使用 PHP 变量变量。丑得要命,但也不是特别丑……