Home >>PHP Object Oriented >PHP Parametrized Function
Parametrized function are used at run time of the program when output depends on dynamic values given at run time
There are two ways to access the parametrized function:
call by value : (here we pass the value directly )
call by reference : (here we pass the address location where the value is stored)
The following example will write different first names, but equal last name
<?php function writeName($fname) { echo $fname ."<br>"; } echo "My name is "; writeName("Durgesh Pandey"); echo "My sister's name is "; writeName("Poonam pandey"); echo "My brother's name is "; writeName("Monu Pandey"); ?>
in the above example1 There is a parametrized function named writeName() that contains 1 parameter . In the first line we have printed a string message.and in the second line we have called the function along with the parameter value. The given example add( ) and sub( ) has two parameters so pass two argument when call add( ) function and sub( )function.
<?php //create add() function with two parameter function add($x,$y) { $sum=$x+$y; echo "Sum=".$sum."<br>"; } //create sub( ) function with two parameter function sub($a,$b) { $sub=$a-$b; echo "Sub=".$sub; } //call function, passing two argument add(1000,2000); sub(1500,500); ?>
in the example2 there are two parametrized function namely add() and sub() both containing two parameters. at the time of calling these function , we have passed both these arguments.
<?php //create add() function with two parameter function add($x,$y) { $sum=$x+$y; echo "Sum=".$sum."<br>"; } //create sub( ) function with two parameter function sub($a,$b) { $sub=$a-$b; echo "Sub=".$sub; } //call function,get two argument through input box when click on add or sub button if(isset($_POST['add'])) { //call add() function add($_POST['f'],$_POST['s']); } if(isset($_POST['sub'])) { //call add() function sub($_POST['f'],$_POST['s']); } ?> <form method="post"> Enter first number <input type="text" name="f"/><hr/> Enter second number <input type="text" name="s"/><hr/> <input type="submit" name="add" value="ADD"/> <input type="submit" name="sub" value="SUB"/> </form>
in example 3 there are two parametrized function namely add() and sub() both containing two parameters. at the time of calling these function , we have passed both these arguments by using HTML form. there are 2 buttons add and sub .the output of the program is based upon the clicking of button by the user at run time. i.e if user click on add button the add function get called.
To let a function return a value, use the return statement.
<?php //create add() function with two parameter function add($x,$y) { $sum=$x+$y; return $sum; } echo "84 + 16 = " . add(84,16); ?>