Wednesday, 7 January 2015

Return Type Functions and Non Return Type Functions




Return type functions in php are those that return the values, you can return any type of values whether simple values, arrays or even objects can be returned. When the return keyword is called in a function its execution is stopped immediately and the control of program is shifted to the point where function is called. Below is the example of return type function
<?php
Function square($a)
{
Return $a*$a;
Echo “inside square function”;
}
Echo square(5);
?>
The output of above program will be simply 25, it will not print  “inside square function” statement, because when the function is called it returns the square from line one to the calling point.
And if we will not use the return keyword in the function then it will not return back control to calling point and will also print the 2nd statement.
Call by value and call by reference
In functions we have two things call by value and call by reference, call by value means the variables which are passed in the function are called by their values only, function don’t need to do anything with the memory address of the variable( means where the variable is stored in the memory). If any change is done to the passed variables inside the function it will not be reflected in the outer variables. 

And call by reference means the variables which are passed to the function are called by their reference means, they are called from their original memory address location, and if any change is done in that variable inside the function, that change will also be reflected in the outer variable. It will be cleared by the following examples:-
Call by value
<?php
Function increment ($a)
{
$a++;
Echo “value of a is ”.$a;
}
$x=10;
Increment($x);
Echo “value of  variable x is ”.$x;
?>
Output of above program is:-
Value of a is 11
Value of x is 10
Call by reference

<?php
Function increment (&$a)
{
$a++;
Echo “value of a is ”.$a;
}
$x=10;
Increment($x);
Echo “value of  variable x is ”.$x;
?>
Output of above program is:-
Value of a is 11
Value of x is 11
In the above two programs, in first program we are passing the value of variable x to function increment, so when the value is incremented in the function it does not affected the variable x.

But when the same function is called by reference, in the 2nd function we are passing the address of the variable in function increment by using the & sign, so when the function is called variable x address is passed to the function, and when its value is incremented in the function it also affected the variable x, its value got incremented.
These examples has been provided by the webcom technologies pvt ltd. The best industrial training institute in Chandigarh, for more information please join us for complete php training program.

No comments:

Post a Comment