What's difference between "&$node" and "$node" or "&$form_state “and "& $form_state"? thanks

Comments

tbenice’s picture

Arguments can be passed to functions either by 'value' or by 'reference'; in a function definition an argument passed by value looks like:

function foo($argument)

and one passed by reference looks like:

function foo(&$argument)

The former means that the function receives only the value of the variable as an argument, so any changes made to that variable in the body of the function are lost when the function closes. However, a reference argument is passed to the function as the 'address' of the variable in memory, thus when the function alters the value, the change 'sticks' and the calling function will note the change.

Thus if you have a function like:

function mymodule_form (&$form_state) {
$form_state['foo'] = 1;
}

and you call that function from another place like:
$form_state = 0;
echo "1: {$form_state}
";
$myval = mymodule_form($form_state);
echo "2: {$form_state}
";

what you will get for output will be:
1: 0
2: 1

Ted S. Benice, PhD
Research & Development
ted@bythewaylabs.com
http://bythewaylabs.com

ludo1960’s picture

Explanation!

huangweiqiu’s picture

I understood, thanks a lot!