PHP Unlimited Arguments
Wed, 13 Oct 2010Sometimes you'll have a function that needs the option to pass any number of arguments, and resorting to an array simply will not do.
In Python you would use an Asterix, like def functionName(*args), though this isn't about python -- Just by looking at that syntax makes it easy to see what we are doing.
So in PHP, you can count how many arguments are passed simply with func_num_args:
function foobar()
{
echo func_num_args();
}
foobar(); // Outputs 0
foobar(1, 'hello', 'hey'); // Outputs 3
You can return the items with func_get_args:
function foobar()
{
// This produces an Array
echo func_get_args();
}
foobar(1, 'hello', 'hey'); // Outputs Array
Here's another example that would allow your argument to chain off custom functions, this is not something I'd actually do but it will let you see another way of working.
function foobar()
{
$total = func_num_args();
for ($i = 0; $i < $total; $i++)
{
$run = func_get_args($i);
$run();
}
}
function Chat()
{
echo 'chatting ';
}
function Run()
{
echo 'running';
}
foobar('chat', 'run'); // Outputs chatting running
I've only found use for this in a few situations, no need to force use of this, it's just nice to have in the back of your mind.