Sunday, September 3, 2017

PHP Default Argument Function


Like C++, PHP has default argument functionality. In which function parameter set with some default value, if you don't pass any value to the function, it will use default argument value.

lets see the simple example using php default argument function.

Example -1 :
<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee()."<br/>"; //calling function with no parameter
echo makecoffee(null)."<br/>"; //calling function with null value as parameter
echo makecoffee("espresso")."<br/>"; // calling function with some value
?>
Output :-
--------------------
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

Example -2 :
<?php
function makecoffee($type = "cappuccino",$cost = 10)
{
    return "Making a cup of $type and it's cost is $cost Dollar. \n";
}
echo makecoffee()."<br/>"; //calling function with no parameter
echo makecoffee(null)."<br/>"; //calling function with null value as parameter
echo makecoffee("espresso",200)."<br/>"; // calling function with some value
?>
Output:
------------------
Making a cup of cappuccino and it's cost is 10 Dollar.
Making a cup of and it's cost is 10 Dollar.
Making a cup of espresso and it's cost is 200 Dollar.

Example - 3 :
<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}
 
echo makeyogurt("raspberry");   // works as expected
?>
Output :
------------------
Making a bowl of acidophilus raspberry.

Note:
when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.


No comments:

Post a Comment