2

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?

Community
  • 1
  • 1
fbiville
  • 8,407
  • 7
  • 51
  • 79
  • 2
    it is very rare that you would ever actually want to use an amp in PHP. objects and resources are passed by reference automatically. – dqhendricks Apr 15 '11 at 21:54
  • Objects are indeed passed by reference... since PHP5. In PHP4, this wasn't the case. That's why you'll see a lot of this in PHP4 code, and very little of it in PHP5. – Frank Farmer Apr 15 '11 at 22:00
  • *(related)* [What does that symbol mean in PHP](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon Apr 15 '11 at 22:06

0 Answers0