Tuesday, 17 September 2013

PHP use variable to pass multiple arguments to function

PHP use variable to pass multiple arguments to function

I have a function that expects 9 arguments to be passed to it. The first
argument it expects is a string, the rest are ints.
Here is the function:
getProductPrice('red', 8, 1.6, 2.15, 0, 0, 0, 17.6, 0);
When that gets run, it works fine. However, when I run it like this:
getProductPrice("'red'".','.$arguments);
It does not work.
"'red'".','.$arguments
outputs: 'red', 8, 1.6, 2.15, 0, 0, 0, 17.6, 0
If anyone could tell me how to use the $arguments variable in place of all
the arguments?
What I ended up suspecting was making it not work, is that what $arguments
is outputting is a string, so I looked into how to convert a comma
separated string of numbers into a php function's arguments.
I came across this:
$params = explode(',', $str);
call_user_func_array("func", $params);
I can't figure out how to use this solution for two reasons:
1. I need to pass a string along with the numbers.
2. simply putting my function name where it says "func" in that example
won't work, because it's a cakephp function, which requires me to put
$this->ModelName->functionname, which breaks the first argument in the
call_user_func_array function()
Any ideas how to help me guys?
I could just put the variables that make $arguments output what it does,
but it's a ton of complicated logic and math to get each of those numbers,
so my function calls would look ridiculous.
Thanks again.

No comments:

Post a Comment