views:

3447

answers:

2

Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I'm working with something like this:

function foo($a1 = null, $a2 = null, $a3 = null, $a4 = null){
    if ($a1 !== null) doSomethingWith($a1, 1);
    if ($a2 !== null) doSomethingWith($a2, 2);
    if ($a3 !== null) doSomethingWith($a3, 3);
    if ($a4 !== null) doSomethingWith($a4, 4);
}

But I was wondering if I can use a solution like this:

function foo(params $args){
    for ($i = 0; $i < count($args); $i++)
        doSomethingWith($args[$i], $i + 1);
}

But still invoke the function the same way, similar to the params keyword in C# or the arguments array in JavaScript.

A: 

http://us2.php.net/array_walk is what you're looking for.

Visage
No, it's not really.What I really wanted was to be able to go from code like in sample 1 to code like in sample 2 without changing any calls to the function.
MiffTheFox
+13  A: 

func_get_args returns an array with all arguments of the current function.

bb
Thank you! This is it!
MiffTheFox
One gotcha with func_get_args that's worth pointing out; you can't pass it into another function call.
Rob
@Rob You can if you go `$args = func_get_args()` and then `call_user_func_array($func, $args)`
alex