function quesiton

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
toshesh
Forum Commoner
Posts: 33
Joined: Thu Jun 19, 2003 9:32 pm

function quesiton

Post 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?
Tubbietoeter
Forum Contributor
Posts: 149
Joined: Fri Mar 14, 2003 2:41 am
Location: Germany

Post 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.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

You can also use an ampersand (&) before a variable name in the function header to specify pass-by-reference behavoir.
toshesh
Forum Commoner
Posts: 33
Joined: Thu Jun 19, 2003 9:32 pm

Post by toshesh »

ahh yes!! is the & same as using the array as a global variable explained before?
Post Reply