Functions with a variable number of arguments

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MattSheppard
Forum Newbie
Posts: 4
Joined: Tue Oct 04, 2011 8:30 am

Functions with a variable number of arguments

Post by MattSheppard »

Hi everyone,

This is something I've seen done in other people's code, but the code has been too complex for me to understand; how do you code a function to accept a variable number of arguments, so that

Code: Select all

DoThisFunction($var1, $var2, $var3);
and

Code: Select all

DoThisFunction();
Would both be valid?

Thanks in advance,
Matt
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Functions with a variable number of arguments

Post by VladSun »

If you know the maximum number of arguments, then use optional variable declaration:

Code: Select all

function DoThisFunction($var1 = null, $var2 = null, $var3 = null)
if not use http://www.php.net/manual/en/function.func-get-args.php . Take a look at the example.
There are 10 types of people in this world, those who understand binary and those who don't
MattSheppard
Forum Newbie
Posts: 4
Joined: Tue Oct 04, 2011 8:30 am

Re: Functions with a variable number of arguments

Post by MattSheppard »

That's brilliant, thank you very much! Just what I was looking for :)
Post Reply