Monday 26 April 2021

Php: Functions: pass the argument by reference

If you pass an argument to the function by reference, any changes made to the variable inside the function are visible outside also.

 

Example

function square(&$a){

    $a = $a * $a;

}

 

In the above snippet, square function expecting a variable reference(same is conveyed to php using &).

 

function_pass_by_reference.php

#!/usr/bin/php

<?php
    function square(&$a){
        $a = $a * $a;
    }

    $ele = 10;

    echo "Value of ele : $ele\n";
    echo "Calling square function\n";

    square($ele);
    echo "Value of ele : $ele\n";
?>

 

Output

$./function_pass_by_reference.php 

Value of ele : 10
Calling square function
Value of ele : 100

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment