Jump to content

clarify use of &$


onlyican

Recommended Posts

Hey people

 

I know what &$ does, it allows you to pass a variable into a function which will update the varibale

 

But please tell me which method is correct or best

 

Option 1:

Add & when calling the function

<?php
function MyFunction($MyVar){
$MyVar = "How are You";
}
$MyVar = "Hello";
MyFunction(&$MyVar);
echo $MyVar;
?>

 

Option 2:

Add & when building function

<?php
function MyFunction(&$MyVar){
$MyVar = "How are You";
}
$MyVar = "Hello";
MyFunction($MyVar);
echo $MyVar;
?>

Option 3:

Add & in both

<?php
function MyFunction(&$MyVar){
$MyVar = "How are You";
}
$MyVar = "Hello";
MyFunction(&$MyVar);
echo $MyVar;
?>

As you can guess, I want the result to be "How are You"; not "Hello";

 

//Edit, Added php tags

Link to comment
https://forums.phpfreaks.com/topic/63930-clarify-use-of/
Share on other sites

As far as im aware, option 2 & 3 are the same. The only differant behaviour with option one is that it allows you to not always pass by reference. Wether or not there would be a time that having a function which sometimes passes by reference and sometimes by value would be useful/required, im not sure.

Link to comment
https://forums.phpfreaks.com/topic/63930-clarify-use-of/#findComment-318641
Share on other sites

The & symbol indicates the address of the variable. Option 1 is the best.

 

For option 1 you are simply passing the address of a variable to a (or any) function.

For option 2, not mater what variable you use, it will always reference the address of it, making it difficult to keep the variable scopes in order.

For option 3, I am actually surprised that it works. If php were a lower level language, I would expect that to change the address of the variable to something completely wrong, rendering it pretty much useless. Since it is PHP, I am would guess that it ignores the second &, making option 3 the same as 2.

Link to comment
https://forums.phpfreaks.com/topic/63930-clarify-use-of/#findComment-318644
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.