Default arguments in the functions of PHP

Posted on May 27, 2008 
Filed Under php, tips and technique, tutorial

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.

Popularity: 8% [?]

Enter your email address and get recent tutorials, tips, tricks and scripts of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Follow me on twitter at http://twitter.com/roshanbh.

Related Posts

» Change default directory page using .htaccess
» Solving ‘Warning: Cannot add header information’ in PHP
» Web Services and PHP - SOAP vs XML-RPC vs REST
» 7 Useful functions to tighten the security in PHP

Comments

One Response to “Default arguments in the functions of PHP”

  1. Default arguments in the functions of PHP on May 27th, 2008 9:15 am

    [...] techsupport@idealbite.com wrote an interesting post today onHere’s a quick excerptIf 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 … [...]

Leave a Reply