Possible Duplicate:
What does it mean to start a PHP function with an ampersand?
I would like to share what I think to know and what I don't understand about the ampersand in PHP language (version < 5.3).
I think I know the basic usage, e.g.:
$var = 'foo';
echo $var; //output foo
$var2 = &$var;
$var2 = 'bar';
echo $var2; //output bar
So far, so good. Let's try with objects:
class Person {public $name='john';}
$person = new Person();
echo $person->name;//outputs john
$person2 = &$person;
$person2->name = 'doe';
echo $person->name;//obviously outputs doe
Note that the above code leads to the same result without the ampersand, given both $person
and $person2 (= $person)
refer to the same object (as in Java), so any change on the object will be retrieved by both variables.
So far, I can say the ampersand operator is only useful for primitives. However, there is something I just don't understand.
Although, I understand this usage:
function superplusplus(&$base) {$base++;}
$var = 2;
superplusplus($var);
echo $var;//outputs 3
What I don't get is this is the usage of ampersand like below:
function &superplusplus($var) {$var++;}
It doesn't seem to have any effect, as if there was no ampersand at all.
What is this syntax supposed to do?