Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.