John Davidson

function - Passing Argument by Reference in PHP

0 comments
Message:


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



My Answer:
In PHP, when you pass a variable by reference to a function, any changes made to the variable within the function will affect the original variable outside of the function. However, in your code, you are not actually modifying the variable $str within the function increment.

The function strtoupper() returns the modified string, but you are not assigning it back to the variable $str within the function. That's why the original variable $str remains unchanged.

To modify the original variable $str within the function, you should assign the result of strtoupper() back to the variable $str like this:

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


By doing this, the original variable $str will be modified to "CIAO" as expected.

Rate this post

3 of 5 based on 1146 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us