tags:

views:

50

answers:

4

A quick beginner's question in PHP.

What does & in &$data do and what are differences with $data?

function prepareMenu(&$data) {
 $this->db->where('parentid',0)
...
...
+4  A: 

&$data is passed by reference, $data is passed by value

Passed by reference - you are passing a reference to the object, not copy. You are using the same object in the caller.

passed by value - you copy the object and pass it to the function. You are working with a copy of the object, different from the object in the caller.

Svetlozar Angelov
this is specially helpfull when working with object instances, if you need to use the instance in a function but mantain the changes to the instance in order to use them later on.
yoda
It's not necessary to pass objects by reference, in PHP 5 at least
Ben James
If you mean by "it's not necessary to pass objects by reference, in PHP 5" that passing by reference is the default in PHP5, then that is not entirely true: they're aliases. See http://nl3.php.net/manual/en/language.oop5.references.php
Elise van Looij
+1  A: 

The & in &$data marks it as a reference.
http://docs.php.net/references explains how they work in php.

VolkerK
+1  A: 

In the simplest terms I can muster:

& - Pass By Reference

Passing a variable by reference means you are passing a copy of the memory address the variable uses to store it's data. PHP has an entire section on their website dedicated to explaining this entitled "References Explained".

This simply means that you can modify the original variable from a secondary source.

Example

function testFunction(&$param) {
    $param = 'test2';
}

$var = 'test';
echo $var; // outputs 'test'
testFunction($var);
echo $var; // outputs 'test2'
cballou
+2  A: 

An example of what the result of this is, would be, if you ran the following program:

$data = 3;
print($data);
prepareMenu($data);
print($data);

function prepareMenu(&$data) 
{
  $data = 7;
  print($data);
}

You would get the output:

3
7
7

Whereas if you passed by value, rather than by reference:

$data = 3;
print($data);
prepareMenu($data);
print($data);

function prepareMenu($data) 
{
  $data = 7;
  print($data);
}

You would get the output:

3
7
3

As in the second example, the value in $data would be copied for use in prepareMenu, as opposed to the first example where you're always working with the original $data

Note: Haven't written PHP in years, so don't expect this to actually compile, it's meant as an example only =)

Rob
Note: References in PHP have some similarities to pointers in C, but they are not the same thing. In particular, there is generally no performance gain in using references. Because of the odd side effects of references, they should rarely be used.
troelskn