How to pass variable by reference in php ?

Discussion in 'Programming/Scripts' started by Prahlad Makwana, Dec 24, 2019.

  1. Hello Everyone, I try to pass variable reference in method but variable reference are not pass in method.
    Please help me for that.
    My code is below :-

    Code:
    <?php
    
    $b=10;
    $a=5;
    
    method_A($a);
    method_b($a,$b);
    
    function method_A($var1)
    {
        echo $var1++ . "\n";
    }
    
    function method_b($var1, $var2)
    {
        echo $var1++ . " And " . $var2++;
    }
    
    ?>
    
    Advance Thanks.
     
    Last edited: Dec 24, 2019
  2. till

    till Super Moderator Staff Member ISPConfig Developer

    What about using Google or any other search engine of your choice? Just enter the title of your post.
     
  3. Harsh Shah

    Harsh Shah Banned

    Hi
    For passing reference of a variable you have to use & sign in method parameter. Find below code. i have modified your code.

    Code:
    <?php
    
    $a=5;
    $b=10;
    
    method_A($a);
    method_b($a,$b);
    
    function method_A($var1)
    {
        echo  "a before: " . $var1++ . "\n";
    }
    
    function method_b(&$var1, $var2)
    {
     $var1 = 10;
        echo "a After changing it value to 10: \n" . "a: " . ++$var1 . " And b:" . $var2++;
    }
    ?>
    
    Here, i have passed reference of $a variable to the function_method_b. Then i changed $a's value to 10. so output of $a is now 10. and output of $b will be as it is because i didn't changed that value.
    Hope this will help you.
    Thank you.
     

Share This Page