Page 1 of 1

function quesiton

Posted: Thu Jul 17, 2003 12:44 am
by toshesh
hi all,

does parsing an array to a function actually copy everything in the array to another array? Is there anyway round this? i.e. just send the location of the array (array pointers?)

I was wondering if I globilize the array and use the global array inside the function would this still copy the array values?

e.g.

global $arr;
$arr = ("asdf", "asdg","bsdf");

function test() {
global $arr;
do something;
}

test();

instead of

function test($arr) {
do something;
}

$arr = ("asdf", "asdg","bsdf");
test($arr);

what's the difference?

Posted: Thu Jul 17, 2003 12:54 am
by Tubbietoeter
the difference is, if you call a function with an array like this: test($arr) then every changes you do to the array are only valid within the function. the function gets only a clone of the array so the changes will be deleted when leaving the function.

if you use global variables and change them from within a function, the changes will be permanent.

you don't need to declare them global before first using them. just declare them global at the top of the functions which use a global variable.


another thing, sometimes it is just useful to be able to call a function with a certain parameter, e.g. when calling a function for each element of an array to calculate something. it depends on the applikation what you chose.
also, when calling a function like this test($variable) the internal name of $variable can be another one:
function test($string) {
echo $string;
}



anyways, in c/c++ it is a convention that you only use global variables where you must, and i think this applies for php as well. use globals where you must and locals where you can.

Posted: Thu Jul 17, 2003 8:13 am
by nielsene
You can also use an ampersand (&) before a variable name in the function header to specify pass-by-reference behavoir.

Posted: Thu Jul 17, 2003 9:16 pm
by toshesh
ahh yes!! is the & same as using the array as a global variable explained before?