tags:

views:

107

answers:

5

Is there a way to pass an unlimited amount of arguments to a function, and access all of those arguments without needing to define each one in the heading. Here is an example to make it more clear:

function doSomething($var1="", $var2="".........)
{
    // Do something with the arguments
}

I don't want to have to go define a bunch of arguments. Is there a way to just grab all the arguments in an array? Even if they haven't been defined? (PHP BTW)

The end result should look something like this:

func("hello", "ya", "hi", "blah", "test", "go");

function func()
{
   //Loop Over Arguments
}

I've seen some native PHP functions be able to accept a seemingly infinite number of arguments, but can user-defined functions do the same?

+3  A: 

See func_get_args. It does exactly what you want

Yacoby
Thanks for being so fast to respond.
Chacha102
+2  A: 

Yes, there definitely is. Check out func_get_args(), it should do exactly what you need.

zombat
+5  A: 

You can use func_get_args, func_get_arg, and func_num_args

Considering you have declared these three variables :

$param_1 = "A";
$param_2 = "B";
$param_3 = "C";

Here's a first example, using func_get_args to get all the parameters in one array :

my_function_1($param_1, $param_2, $param_3);

function my_function_1()
{
    $num_args = func_num_args();
    if ($num_args >= 1) {
        $args = func_get_args();
        var_dump($args);
    }
}

And here's another one to get the parameters one by one, with func_get_arg :

my_function_2($param_1, $param_2, $param_3);

function my_function_2()
{
    $num_args = func_num_args();
    if ($num_args >= 1) {
        $args = func_get_args();
        for ($i = 0 ; $i<$num_args ; $i++) {
            var_dump(func_get_arg($i));
        }
    }
}
Pascal MARTIN
A: 

You can find out how many arguments the function was called with by using func_num_args(). You can then get each argument by specifying its index by using func_get_arg(index), or all arguments as an array by using func_get_args().

Example:

function variable_arguments() {
    echo "This function was called with ".func_num_args()." arguments.<br />";
    echo "Those arguments were:<br /><pre>";
    echo print_r(func_get_args());
    echo "</pre>";
}

variable_arguments("Hello", 42, array(true));
Jon
A: 

As others have posted before you can use func_get_args() but why not try to pass the parameters in an array? PHP is loosely typed so you can store anything in it.

$params = array(1, 2, 'something');
doSomething($params);

function doSomething($params) {
    foreach ($params as $value) {
    // do something.
    }
}

I prefer this because it makes visible to the developer that you expect parameters for the function and you still can pass as many parameters as you like with little overhead via the paramters array.

capfu