0

Is there a way to turn an associative array into parameters for a function.

I have a simply array such:

$arr = [
  'id' => 321654,
  'name' => 'action1'
];

I have a static function in a class:

class someclass{
  static function someFunction( $id, $name ){
     //the rest of the method
  }
}

I can call the class by variables, eg:

$class = 'someclass';
$method = 'somFunction';

return $class::$method(  );

I can also pass is in a definite qty of function parameters, or an array

return $class::$method( $arr );

In this example's case I could hard code the params to:

return $class::$method( $arr['id'], $arr['name'] );

But how would i pass an unknown qty of keys. Another run may contain 1 key or 4 or 10...

5
  • Which PHP version are you using? Commented Apr 9, 2016 at 14:11
  • 2
    Take a look at call_user_func_array Commented Apr 9, 2016 at 14:11
  • I think @Rizier123 possibly meant func_get_args - either way check here php.net/manual/en/… Commented Apr 9, 2016 at 14:18
  • return call_user_func_array( ''.$class.'::'.$method, $params ); Worked a charm. Adding to Q Commented Apr 9, 2016 at 14:24
  • @John Yey, you got the solution! But please see: stackoverflow.com/help/self-answer answers in the answer section :) Commented Apr 9, 2016 at 14:28

1 Answer 1

1

Thanks to @Rizier123 comment:

This worked very nicely:

call_user_func_array( ''.$class.'::'.$method, $arr );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.