Default arguments in the functions of PHP

Advertisement

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: 3% [?]

Tags:

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

Related Posts

» Change default directory page using .htaccess
» Solving ‘Warning: Cannot add header information’ in PHP
» Solving Floating point number precision lost problem in PHP
» Web Services and PHP – SOAP vs XML-RPC vs REST

2 Comments on “Default arguments in the functions of PHP”

  • Muazam wrote on 24 January, 2010, 16:59

    usefull, thx.

Trackbacks

  1. Default arguments in the functions of PHP

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.