1

I am trying to pass array to a method and I want the method use array's values as arguments.

I posted a similar question on How to assign arrays to functions arguments? thread but I am actually working on the class method here.

if (method_exists($testInstance, $method)){
  $a=array {'1'=>'aru1', '2'=>'arg2'}   //could have more than 2. it's dynamic
  call_user_func_array($testInstance->$method(), $a);  //this won't work.
}

Any thoughts? Thank a lot!

Community
  • 1
  • 1
FlyingCat
  • 14,036
  • 36
  • 119
  • 198
  • possible duplicate of [How to assign arrays to functions arguments?](http://stackoverflow.com/questions/10576318/how-to-assign-arrays-to-functions-arguments) – John Conde May 14 '12 at 01:18
  • 2
    Mmmh... have you considered reading the documentation (second example)? http://php.net/manual/en/function.call-user-func-array.php ... also it is helpful to follow further links, read about `callbable`: http://www.php.net/manual/en/language.types.callable.php – Felix Kling May 14 '12 at 01:19
  • possible duplicate of [Passing an Array as Arguments, not an Array, in PHP](http://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php) -- second answer. – Felix Kling May 14 '12 at 01:20
  • @FelixKling It seems only work in Static method. Am I wrong? – FlyingCat May 14 '12 at 01:25
  • are you really assigning array using `{}`? – Andreas Wong May 14 '12 at 01:26
  • 1
    Works perfectly fine with normal methods. The example shows: `/* Call the $foo->bar() method with 2 arguments*/ $foo = new foo; call_user_func_array(array($foo, "bar"), array("three", "four"));`. Also this has been asked before and this is the answer: http://stackoverflow.com/a/745112/218196. Why do you think the method must be static? – Felix Kling May 14 '12 at 01:27
  • @NiftyDude no man, just typo. – FlyingCat May 14 '12 at 01:27
  • @Jerry ok just making sure :) – Andreas Wong May 14 '12 at 01:27
  • @FelixKling Ty. totally my bad. Should have noticed that. +1 – FlyingCat May 14 '12 at 01:30

1 Answers1

3

As Felix suggested you need to pass a callable. For a class method that is an array with the object inatance (or class name if it is a static method) and the method name:

call_user_func_array(array($obj,'myMethod'), $args)

prodigitalson
  • 60,050
  • 10
  • 100
  • 114