2

I have a question regarding PHP. Is there any way I could make a function, which has a dynamic number of function inputs?

For example, let's call that function dynamic_func()

It should work in both of these cases, and also in other cases, not depending on number of functions input:

 dynamic_func(1,2,3,4)
 dynamic_func(1,2,3,4,5,6)

Thanks in advance!

1
  • For that example you could just pass them all as an array to the function as a single argument. But I presume you'll want something slightly more complicated than that in the long run. Commented Jun 21, 2011 at 11:54

3 Answers 3

4

It works as normal.

function dynamic_func()
{
  $args=func_get_args(); //get all the arguments as an array
}

dynamic_func(1,2,3,4); //will work
dynamic_func(1,2,3,4,5,6); //will work
Sign up to request clarification or add additional context in comments.

Comments

3

I believe PHP will never complain if you pass more arguments than those expected by a function. E.g.:

<?php
function foo($a) {
}
foo();         // invalid (Warning: Missing argument 1 for ...)
foo('a');      // valid
foo('a', 'b'); // surprise... valid!

So you can use func_get_args() and func_num_args() inside foo() to detect how many parameters were actually passed on to that function:

<?php
function foo(/*$a*/) {
    echo func_num_args();
    var_dump(func_get_args());
}
foo('a', 'b');

Rest is up to you.

Comments

0

there are two possibilitys to do this: using func_get_args like Shakti Singh explained or predefine the arguments like this

function myfunc($arg1 = 1, $arg2 = 2, $arg3 = 3){
  echo $arg1.' '.$arg1.' '.$arg3;
}
myfunc(); // outputs "1 2 3";
myfunc(9,8); // outputs "9 8 3";

note that you can set the arguments to any default value that is used if the argument isn't given, but you'll have to define all arguments with this - it isn't as dynamic as using func_get_args.

Comments

Your Answer

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