Home > Back-end >  Passing Argument by Reference in PHP
Passing Argument by Reference in PHP

Time:10-26

I started studying PHP and I have a question about passing arguments by reference in a function.

I wrote this code:

<?php
    $str = "ciao";
    increment($str);
    
    function increment(&$str){
        strtoupper($str);
    }
    echo $str."\n";
?>

The result is "ciao" instead of "CIAO".

Why if I pass a variable, like $str, by reference to a function, the original variable dosen't come modify?. I though String $str is immutable in php (like Java) but it's not so. To modify the original value I should write

$str=strtoupper($str);

instead of

strtoupper($str);

So, in general, why if I pass an argument by reference in a function in PHP I have to save in the same varible the modify that i do in the function's body?

I hope to be clear, thanks

Luca

CodePudding user response:

strtoupper() returns the result of its action, so you need to put that result back into the variable regardless of wether that variable is passed by reference or not.

function increment(&$str){
    $str = strtoupper($str);
}

CodePudding user response:

The issue here is not with passing an argument to reference, but how strtoupper itself works.

If instead of strtoupper you were doing something else, such as this

<?php

function increment(&$num)
{
    $num  ;
}

$n = 1;
increment($n);

echo $n."\n";

you would see that the $n variable outside is changed by the function.

But strtoupper doesn't modify the variable in place: it returns the uppercased value instead.

So that's why you need to reassign the value returned by strtoupper to the variable:

<?php
    $str = "ciao";
    increment($str);
    
    function increment(&$str){
        $str = strtoupper($str);
    }
    echo $str."\n";
  • Related