2

This page of the PHP Manual says that only a named variable can be assigned by reference, http://www.php.net/manual/en/language.variables.basics.php. It gives the example that $bar = &$foo; is a valid assignment, but $bar = &(24 * 7); is not.

In the page on variable scope however, http://www.php.net/manual/en/language.variables.scope.php, it gives an example of $obj = &new stdclass;.

How can this be so? new stdclass is not a named variable!

Thanks...

DatsunBing
  • 8,684
  • 17
  • 87
  • 172
  • in PHP5, the use of `&` is not necessary anymore. it is only preserved for backwards compatibility. http://stackoverflow.com/questions/8490836/php-returning-references-necessary-in-caller – Joseph Feb 26 '12 at 11:35
  • Very important here is that that is only the case of **objects**, 'regular' variables (numbers, strings, arrays), are not passed by reference by default, only objects are. – MichD Feb 26 '12 at 11:39

2 Answers2

1

The new construct is a little special with references:

$obj = &new stdclass;

Actually it's not recommended to do this any longer (that's PHP 4 code), you should write it as such:

$obj = new stdclass;

However for the sake of the argument and your question, there is also return by referenceshy;Docs which is passing the said named variable as the return value of a function:

$obj = &someFunction();

As you can imagine, this could work with other language constructs as well. The important point is, if there is a reference, there must be some variable. Without a variable you can't have a reference in PHP.

hakre
  • 193,403
  • 52
  • 435
  • 836
1

It's a little explained here: http://www.php.net/manual/en/language.references.whatdo.php

"The same syntax can be used with functions that return references, and with the new operator (since PHP 4.0.4 and before PHP 5.0.0):"