tags:

views:

136

answers:

4

I have this code

$myNewClass->cars =& Orders_Car::GetRecords($myNewClass->searchString);
                   ^

what is & doing there. thanks

+6  A: 

It changes the variable to be 'passed by reference'. This is as opposed to passing a copy of the variable in.

See the manual for details.

One common use is in foreach.

Typically, foreach operates on a copy of the iterable array or object.

That means

$salad=array(1,2,3);
foreach ($salad as $leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 1   

foreach ($salad as &$leaf){
  $leaf+=1;
  }
echo $salad[0];// output: 2 because & made the assignment affect the original array
Alex JL
Note that you can also assign by reference:`$a =` will mean that when you do `$b = 1;`, `$a` will automatically change to be 1
phsource
... and return by reference. That's why I voted up greg0ire instead.
Artefacto
That's true, there's a lot more to it than passing by reference, I guess. Perhaps someone would like to create an answer that covers all of these aspects, more than just a link to the docs? On the other hand, I'd guess that this question is a duplicate of a duplicate of a duplicate.
Alex JL
+6  A: 

It creates a reference. If you don't know what a reference is, read this : http://www.php.net/manual/en/language.references.php

greg0ire
+4  A: 

Read Do not use PHP references by PHP expert Johannes Schlüter

PHP references are a holdover from PHP 4, where objects were passed by value instead of by reference unless you deliberately made them by reference. This isn't necessary when using PHP 5, because all objects are passed by reference in PHP 5 all the time.

Scalars and arrays are still passed by value by default in PHP 5. If you need to pass them by reference, you should just use an object.

Bill Karwin
This is not entirely correct, there are valid uses for references in PHP 5 (e.g. building a graph-like structure on arrays, or __get by reference, or foreach example below) - but objects and references should not mix, this is correct.
StasM