In this tutorial, you will learn What is PHP function Pass By Value and Pass By Reference.

Pass By Value

By default, PHP variables are passed by value as function arguments in PHP.

That means when you pass a variable as the function argument and modify this argument it does not affect the original variable.

Example:

<?php
$num = 12;
function myFunc($arg){
    // changing the argument value
    $arg = 7;
    echo "Inside Function - $arg";
}
myFunc($num);
echo "<br>";
echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 12

Pass by Reference

Pass by reference is the inverse of the pass by value, that means when you modify the function argument it will affect the original variable.

Example:

&” Is used to activate pass by reference.

<?php
$num = 12;
function myFunc(&$arg){
    // changing the argument value
    $arg = 7;
    echo "Inside Function - $arg";
}
myFunc($num);
echo "<br>";
echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 7

Leave a Reply

Your email address will not be published. Required fields are marked *