Saturday, September 9, 2017

PHP Call By Reference


In this article I want to discuss about PHP call by reference, Actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.

Let's see the concept of call by reference by the help of examples.

Example -1 :
In this example, Variable $str pass to function concatString(). we have passed ampersand (&) symbol to function definition argument and that makes a change to actual variable.


<?php  
function concatString(&$str2)  
{  
    $str2 .= 'Call By Value';  
    echo "$str2"."<br/>" ;
}  
$str = 'Demo  ';  
concatString($str);  
echo $str;  
?>
Output:
------------------------
Demo Call By Value
Demo Call By Value

Example -2 :

Similarly, we have another example related to call by reference.
<?php  
function increment(&$i)  
{  
    $i++;  
    echo "Inside function :  $i <br/>";
}  
$i = 10;  
increment($i);  
echo "Outside Function : ".$i;  
?>
Output:
-----------------------
Inside function : 11
Outside Function : 11

No comments:

Post a Comment