Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global vs pass by reference 1

Status
Not open for further replies.

spelltwister

Programmer
May 12, 2005
36
US
Hey all,

Is there any advantage to using pass by reference over global declaration in the function?

Here's what I have:

$myArray;

function alterMyArray(){
global $myArray;
//do something to my array
}

function alterMyArray(&$myArray){
//do something to my array
}

alterMyArray($myArray);

The function will only ever have the $myArray variable passed in so, is there any reason to use pass by reference?

Lastly, does the & go in the function signature or in the function call (IE function A(&$byRef){} OR A(&$byRef)Wink

Thanks a bunch!

Mike

Online multiplayer strategy games huh? Try, 1483online.com where the games are FREE and the community drives enhancements to the game. ;-D
 
First, the easy question. The "&" goes in the function definition:

Whether a global or pass-by-reference is better depends on how much code reuse you do. If you intent to include that function from multiple scripts, you will, I think, be better off with a pass-by-reference parameter. The interpreter will remind you if you forget to pass in a necessary parameter. It may not do so if you forget to create the global variable outside the function.

As a standard practice, I use as few "global" variables as possible. I never know when I will need to reuse my code.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top