如何在php中使用数组中的变量参数调用实例变量方法

时间:2021-04-30 13:26:04

I want to call a function with variable length arguments stored in an array. I noticed that you can do this with call_user_func_array($callback, $array); However it doesn't seem to work on instance variable methods.

我想调用一个存储在数组中的可变长度参数的函数。我注意到你可以使用call_user_func_array($ callback,$ array)执行此操作;但是它似乎不适用于实例变量方法。

class foo{
  $iVar 

  function A{
      $anArray = array(...);
      call_user_func_array(iVar->methodName,$anArray);
  }
}

Any suggestions?

有什么建议么?

1 个解决方案

#1


1  

A couple of things are wrong there. First, iVar is not a constant, so it should begin with a $. And since it is a property of foo, it should be $this->iVar.

那里有几件事是错的。首先,iVar不是常数,所以它应该以$开头。因为它是foo的属性,它应该是$ this-> iVar。

Secondly, you cannot pass a function like that. You have to pass it as a callable. So in total, the call should look like this:

其次,你不能传递这样的功能。你必须把它作为一个可调用的。总的来说,调用应该如下所示:

call_user_func_array(array($this->iVar, 'methodName'), $anArray);

#1


1  

A couple of things are wrong there. First, iVar is not a constant, so it should begin with a $. And since it is a property of foo, it should be $this->iVar.

那里有几件事是错的。首先,iVar不是常数,所以它应该以$开头。因为它是foo的属性,它应该是$ this-> iVar。

Secondly, you cannot pass a function like that. You have to pass it as a callable. So in total, the call should look like this:

其次,你不能传递这样的功能。你必须把它作为一个可调用的。总的来说,调用应该如下所示:

call_user_func_array(array($this->iVar, 'methodName'), $anArray);