Saturday, 7 February 2015

Function Return Values

In previous examples we just print the value from functions ,but if we need to do other tasks like need some results of calculations or some statements ,for this type of scenario in php we use return values in function Example:

<?php
// define a function for calculation
function calculate($val1,$val2,$opr) { 
   
if($opr=='add'){
return $val1+$val2;  // return value 
}
if($opr=='sub'){
return $val1-$val2;  // return value 
}
if($opr=='mul'){
return $val1*$val2;  // return value 
}
    

//call a function where first two parameters values and other mention operation you need to perform

$result = calculate(2,5,'mul');  //multiply operation

echo $result; 

//print output 10
?>


Function Passing Values by Refrence

As we discussed in previous e.g what is function passing by value ,in passing by value we can change value of variable by passing values , but if we want to change our global variable value than we use function by reference,in function by reference we pass parameters to function with the reference of variable not the value of variable as mention in below .

Example:

<?php
//declare gloabal variable 
$myvar= "global variable"; 

// function to show the value
function myfunction(&$myparameter) { 
    $changeparameter = "global vaiable inside"; 
    echo "This is $changeparameter  the function<br />"; 

// call function 
myfunction($myvar); 

// print global variable value
echo "This is $myvar outside the function";
 

?>

In above example (&) with parameter use to set reference for variable,it will modify global variable value