Default arguments in the functions of PHP

If you are unaware of default argument in function then you should know that you candefine the function with default arguments in PHP as you can do it C and C++. Providing default arguments in the function can be very useful when you’ve to extend the the functionality of the previously written functions.


Example of using default argument in the function of PHP

Let’s suppose that you’ve already written a function to “calculate the amount collected in day by site”

function getAmountCollected($day)
//code for function goes here

Assume that this function is called from around 20 places in your project. After sometime, your client asked you to find the ” amount collected by site in that date range”. For this case, you need to pass two parameters(start date and end date) to the function.

Do you write another function or extend the functionality of the same function?

I would use the same function for this purpose to minimize the code. But one major problem, we’ve already called the functions from many places with the single argument. How can we define the same function which can be called both with single and double argument? In this case, default argument comes handy,

function getAmountCollected($day, $end_day=’none’)
//code for function goes here

As you can see above, we’ve placed the second argument in this function like “$end_day=’none’“, which is called the default argument of the function. You can call this function with both single and double arguments.

And, when the second argument is not supplied while calling the function, the variable “$end_day” contains “none” value in it. i.e when we call this function called like this with single argument

getAmountCollected(‘2008-05-14′); //remember single argument

then the second parameter will have “none” value in it in the called function.

2 thoughts on “Default arguments in the functions of PHP

  1. Muazam

    usefull, thx.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>