View Single Post
Old 04-24-2009, 01:31 AM   #9 (permalink)
Village Idiot
Wizard
Top Contributor 
 
Village Idiot's Avatar
 
Join Date: Sep 2007
Posts: 1,299
Thanks: 17
Village Idiot is on a distinguished road
Default

Opposed to returning an array by value, it is faster (although trivial on small systems) to pass by reference. This assigns the array to memory and passes the location of the variable to the script. This code should do it.

PHP Code:
function assignArr(&$param)
{
param = array("a","b","c");
}

$arr = array();
assignArr($arr);

echo 
$arr[0] . $arr[1] . $arr[2]; 
$arr will be modified in memory when you pass by reference.

Since I feel like explaining stuff tonight, I will explain how this works.

There are two ways to pass variables in programming, by reference and by value. By value is the most common and often the best way to go, if you dont know which you are doing you are probably passing by this method. This simply copies the value down to a new part of memory. This allows you to modify this copy without touching the original value.

Passing by reference uses special variables called pointers, if you work with C you are very familiar with this. Since all your variables are stored in the ram, they have an address, these variables do not actually contain the value of the variable but memory addresses. So when you need to access the variables, it points the script to the address in memory. This allows you to efficiently modify outside variables though parameters without violating good scope practices.

PHP tries to keep this fairly transparent to you, so you only need to know how to pass by reference. But this will be an unavoidable part of C or C++ if you start larning it.
__________________

Village Idiot is offline  
Reply With Quote