Q:

PHP program to demonstrate the use of default arguments

belongs to collection: PHP Classes & Objects Programs

0

Here, we will calculate the addition of two numbers, here we use on the argument of user define function contains a default value. It means if we will pass the value of the default argument then the default value is used for that parameter.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the use of default arguments is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the 
//use of default arguments.
function Sum($num1, $num2 = 20)
{
    $num3 = $num1 + $num2;
    return $num3;
}

$num3 = Sum(10, 30);
echo "Sum: " . $num3 . "<br>";

$num3 = Sum(10);
echo "Sum: " . $num3 . "<br>";
?>

Output:

Sum: 40
Sum: 30

Explanation:

In the above program, we created a user define function Sum() that contains two arguments $num1 and $num2.

function Sum($num1, $num2=20);

Here, we used $num2 as a default argument, if we pass only one value to the function then 20 will be used for $num2.

$num3=Sum(10,30);
echo "Sum: ".$num3."<br>"; 

In the above code, we pass two arguments then the sum of 10 and 30 assigned to the variable $num3 and printed on the webpage.

$num3=Sum(10);
echo "Sum: ".$num3."<br>"; 

In the above code, we pass only one argument then the sum of 10 and 20 assigned to the variable $num3 and printed on the webpage.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP program to demonstrate the use of variable arg... >>
<< PHP program to demonstrate the call by value param...